How to store values from a function used in a for loop?

2 views (last 30 days)
I am trying to store values generated by a function in a for loop into the OP_vector.
My code:
sigma_one = .2;
sl= .2:.01:.3;
OP_vector = zeros(1,length(sl));
for sigma_one = .2:.01:.3
nle = fsolve(@RegimeSwitch,xx,opts, lambda,row, mu, mu_one, a, b, c, r, gamma, A, sigma_one, beta1,delta1,k);
OP = nle(1,1);
OP_vector=OP;
end
I continually get only one element in the OP_vector.

Answers (1)

Adam
Adam on 21 Aug 2015
Edited: Adam on 21 Aug 2015
sigma_one = .2;
sl= .2:.01:.3;
numValues = numel( sl );
OP_vector = zeros(1,numValues );
for n = 1:numValues
nle = fsolve(@RegimeSwitch,xx,opts, lambda,row, mu, mu_one, a, b, c, r, gamma, A, sl( n ), beta1,delta1,k);
OP = nle(1,1);
OP_vector(n)=OP;
end
should work though I made the changes off the top of my head without testing in Matlab itself so there could be mistakes.
The key point is that to assign to an array you have to use an index into the array, otherwise you are just overwriting a single variable again and again and your pre-sizing of that variable is irrelevant in that case.
Also that index must be an integer, hence why I reworked your loop to use an integer index rather than looping directly on your sl array.
If fsolve allows vector inputs then a vectorised solution would be a lot neater, but I don't know anything about fsolve so I'll leave it at just fixing the for loop.

Tags

Community Treasure Hunt

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

Start Hunting!