将Matlab中的矩阵运算转换为R代码
问题描述:
我试图将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.
答
我曾经在几年前做过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)
不要试图一次转换所有东西,因为您会遇到麻烦。如果结果不匹配,您将无法确定错误的位置。
您可能需要用'%*%'代替'*' – 2014-10-26 18:47:40
,即'%*%'是标准矩阵乘法; '*'表示元素(Hadamard)乘积,相当于MATLAB中的'。*'。 – 2014-10-26 19:03:03
@BenBolker我不知道有一个矩阵元素乘积的名字。我认为它被称为“常识”产品。 :) – 2014-10-26 19:10:22