我試圖將Matlab代碼轉換爲R.我不熟悉Matlab矩陣運算,並且它看起來來自我的R代碼的結果與Matlab的結果不匹配,所以任何幫助將不勝感激。在Matlab代碼,我想轉換爲以下(從this website):將Matlab中的矩陣運算轉換爲R代碼
% 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)
看來,unity*S
在Matlab相當於colSums(S)
在R.但我一直無法弄清楚如何在R中計算S^-1*unity
的等效值。如果我在R(S^-1*unity
)中輸入這個Matlab代碼,它將計算沒有錯誤,但它給出了不同的答案。因爲我不瞭解底層的Matlab計算,所以我不知道如何將它轉換爲R.
您可能需要用'%*%'代替'*' – 2014-10-26 18:47:40
,即'%*%'是標準矩陣乘法; '*'表示元素(Hadamard)乘積,相當於MATLAB中的'。*'。 – 2014-10-26 19:03:03
@BenBolker我不知道有一個矩陣元素乘積的名字。我認爲它被稱爲「常識」產品。 :) – 2014-10-26 19:10:22