1

I'm trying to convert Matlab code to R. I'm not familiar with Matlab matrix operations, and it appears the results from my R code do not match the results from Matlab, so any help would be greatly appreciated. The Matlab code I'm trying to convert is below (from 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)

Here is my attempt in 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)

It appears that unity*S in Matlab is equivalent to colSums(S) in R. But I haven't been able to figure out how to calculate the equivalent of S^-1*unity in R. If I type this Matlab code in R (S^-1*unity), it calculates without error, but it gives a different answer. Because I don't understand the underlying Matlab calculation, I'm not sure how to translate it to R.

itpetersen
  • 1,475
  • 3
  • 13
  • 32

1 Answers1

2

I used to do matlab -> R conversions quite a bit a few years ago.

My general suggestion is to open 2 terminals side by side and try to do everything going line-by-line. Then after each line you should check if what you got in MATLAB and R are equivalent.

This document should be handy: http://mathesaurus.sourceforge.net/octave-r.html

In your case these appear to be the commands that you should have in mind:

Matrix multiplication:

Matlab: A*B
R: A %*% B

Transpose:

Matlab: A'
R: t(A)

Matrix inverse:

Matlab: inv(A) or A^-1
R: solve(A)

Don't try to convert everything at once because you will run into trouble. When the results won't match you will not be able to tell where the error is.

Karolis Koncevičius
  • 9,417
  • 9
  • 56
  • 89