How to store values from a function used in a for loop?
이전 댓글 표시
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.
답변 (1개)
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.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!