2014-10-26 68 views
1

我試圖將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.

+0

您可能需要用'%*%'代替'*' – 2014-10-26 18:47:40

+0

,即'%*%'是標準矩陣乘法; '*'表示元素(Hadamard)乘積,相當於MATLAB中的'。*'。 – 2014-10-26 19:03:03

+1

@BenBolker我不知道有一個矩陣元素乘積的名字。我認爲它被稱爲「常識」產品。 :) – 2014-10-26 19:10:22

回答

2

我曾經在幾年前做過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) 

不要試圖一次轉換所有東西,因爲您會遇到麻煩。如果結果不匹配,您將無法確定錯誤的位置。