[英]Converting matrix operations in Matlab to R code
我正在嘗試將Matlab代碼轉換為R。我不熟悉Matlab矩陣運算,並且看來我的R代碼的結果與Matlab的結果不匹配,因此,我們將不勝感激。 我要轉換的Matlab代碼如下(來自此網站 ):
% Mean Variance Optimizer
% S is matrix of security covariances
S = [185 86.5 80 20; 86.5 196 76 13.5; 80 76 411 -19; 20 13.5 -19 25]
% Vector of security expected returns
zbar = [14; 12; 15; 7]
% Unity vector..must have same length as zbar
unity = ones(length(zbar),1)
% Vector of security standard deviations
stdevs = sqrt(diag(S))
% Calculate Efficient Frontier
A = unity'*S^-1*unity
B = unity'*S^-1*zbar
C = zbar'*S^-1*zbar
D = A*C-B^2
% Efficient Frontier
mu = (1:300)/10;
% Plot Efficient Frontier
minvar = ((A*mu.^2)-2*B*mu+C)/D;
minstd = sqrt(minvar);
plot(minstd,mu,stdevs,zbar,'*')
title('Efficient Frontier with Individual Securities','fontsize',18)
ylabel('Expected Return (%)','fontsize',18)
xlabel('Standard Deviation (%)','fontsize',18)
這是我在R中的嘗試:
# S is matrix of security covariances
S <- matrix(c(185, 86.5, 80, 20, 86.5, 196, 76, 13.5, 80, 76, 411, -19, 20, 13.5, -19, 25), nrow=4, ncol=4, byrow=TRUE)
# Vector of security expected returns
zbar = c(14, 12, 15, 7)
# Unity vector..must have same length as zbar
unity <- rep(1, length(zbar))
# Vector of security standard deviations
stdevs <- sqrt(diag(S))
# Calculate Efficient Frontier
A <- unity*S^-1*unity
B <- unity*S^-1*zbar
C <- zbar*S^-1*zbar
D <- A*C-B^2
# Efficient Frontier
mu = (1:300)/10
# Plot Efficient Frontier
minvar = ((A*mu^2)-2*B*mu+C)/D
minstd = sqrt(minvar)
看來Matlab中的unity*S
等效於R中的colSums(S)
。但是我還無法弄清楚如何計算R中S^-1*unity
的等效值。如果我在R( S^-1*unity
),它的計算沒有錯誤,但是給出了不同的答案。 因為我不了解底層的Matlab計算,所以不確定如何將其轉換為R。
幾年前我曾經做過matlab-> R轉換。
我的一般建議是並排打開2個終端,並嘗試逐行進行所有操作。 然后,在每一行之后,您應該檢查在MATLAB和R中獲得的值是否相等。
該文檔應該方便: http : //mathesaurus.sourceforge.net/octave-r.html
在您的情況下,這些似乎是您應該記住的命令:
矩陣乘法:
Matlab: A*B
R: A %*% B
移調:
Matlab: A'
R: t(A)
矩陣逆:
Matlab: inv(A) or A^-1
R: solve(A)
不要嘗試一次轉換所有內容,否則會遇到麻煩。 當結果不匹配時,您將無法分辨錯誤在哪里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.