【问题标题】:Converting matrix operations in Matlab to R code将 Matlab 中的矩阵运算转换为 R 代码
【发布时间】: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


【解决方案1】:

几年前我曾经做过 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)

不要试图一次转换所有东西,因为你会遇到麻烦。当结果不匹配时,您将无法判断错误在哪里。

【讨论】:

    猜你喜欢
    • 2021-06-03
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    相关资源
    最近更新 更多