MATLAB Answers

0

How do I put a series of sum into a function?

Asked by Dennis Göbel on 19 Apr 2019
Latest activity Answered by Alan Weiss
on 22 Apr 2019
Hi! I am trying to solve the optimization problem for a risk parity portfolio. To be precise:
w is a nx1 vector of portfolio weigths and C th nxn covariance matrix.
The variable port_size is a scalar that returns the number of assets invested in.
I tried to solve it with fmincon, but the first problem that is appearing is that apparently I cannot do the fun_rp = @(w_rp) with the for loop as MATLAB gives me the error: illegal use of reserved keyword "for".
w_mv0 = [0.25; 0.25; 0.25; 0.25];
Aeq = ones(1, port_size);
beq = 1;
lb = zeros(1, port_size);
ub = ones(1, port_size);
fun_rp = @(w_rp) for i = 1:port_size
for j = 1: port_size
(w(1,i)*(C*w(1,i)')-w(1,j)*(C*w(1,j)'))^2;
end
end
w_rp = fmincon(fun_rp,w_rp0,[],[],Aeq,beq,lb,ub)
Does anybody know where my mistake is? I´d appriciate every help!
Best regards

  0 Comments

Sign in to comment.

1 Answer

Answer by Alan Weiss
on 22 Apr 2019
 Accepted Answer

I did not try to run your code, but I have several comments.
  1. Use the appropriate solver for your objective. For a quadratic objective function with linear constraints, the Optimization Decision Table says to use quadprog.
  2. Even if you decide to use fmincon as a solver, you cannot write an objective function using an anonymous function with a loop. Instead, write the loop in a function file, and call the function file with fmincon. For an example, see an introductory example on minimization.
  3. Where do you define C? Or is that your name for your decision variable w_rp?
Good luck,
Alan Weiss
MATLAB mathematical toolbox documentation

  0 Comments

Sign in to comment.