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

조회 수: 1 (최근 30일)
Dennis Göbel
Dennis Göbel 2019년 4월 19일
답변: Alan Weiss 2019년 4월 22일
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

채택된 답변

Alan Weiss
Alan Weiss 2019년 4월 22일
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개)

카테고리

Help CenterFile Exchange에서 Portfolio Optimization and Asset Allocation에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by