How to store output vector from optimizations from a foor loop iterating through a matrix(columnwise)?

I have written an optimization function that returns a weightvector [Nx1]. Now I want to solve the optimization function (which I don't show because it is very complicated) for each of the column-vector in the matrix gamma. These vectors are used in the optimization function. Therefore, i loop trhough the gamma matrix and then want to store each resulting weight vector in a matrix. But that doesn't work because I can't index the matrix_weight with r, because r is a vector. How can I store the result of each optimization in the matrix? The loop works, the solution is just overwritten everytime.||
gamma = [1 2 3 4; 1 1 1 1; 8 1 9 7]';
matrix_weigths = zeros(N,size(gamma,2));
for r = gamma
weights = optimization(Returns, ExpRet, r)
matrix_weights = weights;
end
When I put
matrix_weights (:,r) = weights;
then the folling error occurs: Assignment has fewer non-singleton rhs dimensions than non-singleton subscripts
Does anybody have an Idea how to solve this issue?

4 Comments

Then there is no reason matrix_weights(:,r)=weights; shouldn't work. You can try to find the bug with the debugger. Under the breakpoints button you can select 'pause on error' or 'stop on error'. Enable it and check if the dimensions of matrix_weights and weights are still as expected when the error occurs.
Thanks for the input. These two are of the same dimension though. I think the problem is that for example in the first run: r = [1 2 3 4] and that is why it can't put weights in the matrix_weight because when you refernce matrix_weights(:,r) the r is a vector of 4 elements but it would ned to be a single varibale. So in the first run it needs to be 1 and in the secon run it needs to be 2 etc. I was hoping there was a way to work around this issue.

Sign in to comment.

 Accepted Answer

You indeed need a correct counter to store your results in the matrix. The code below is an example of what you could do.
gamma = [1 2 3 4; 1 1 1 1; 8 1 9 7]';
matrix_weigths = zeros(N,size(gamma,2));
r2=0;
for r = gamma
r2=r2+1;
weights = optimization(Returns, ExpRet, r)
matrix_weights(:,r2) = weights;
end

More Answers (0)

Categories

Asked:

on 27 Feb 2018

Commented:

on 27 Feb 2018

Community Treasure Hunt

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

Start Hunting!