【发布时间】:2014-10-26 18:44:18
【问题描述】:
我正在尝试将 Matlab 代码转换为 R。我不熟悉 Matlab 矩阵运算,而且我的 R 代码的结果似乎与 Matlab 的结果不匹配,因此非常感谢任何帮助。我要转换的 Matlab 代码如下(来自this website):
% 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 中键入此 Matlab 代码(S^-1*unity),它的计算没有错误,但它给出了不同的答案。因为不懂Matlab底层的计算,所以不知道怎么翻译成R。
【问题讨论】:
-
您可能需要将
%*%替换为* -
即
%*%为标准矩阵乘法;*表示逐元素 (Hadamard) 乘积,相当于 MATLAB 中的.*。 -
@BenBolker 我不知道矩阵的元素乘积有一个名称。我认为它被称为“常识”产品。 :)
-
我认为您还需要一个矩阵逆函数(可能是
solve),至少假设^-1是Matlab 中的矩阵逆函数。
标签: r matlab matrix matrix-multiplication