store solutions of a for loop
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi, this is my M-file named nle.m
function F = nle(x,b1,b2)
F = [(1-x(1))*x(2)*30+(1-x(1))*(1-x(2))*150-b1;
x(1)*189+(1-x(1))*x(2)*55.5+(1-x(1))*(1-x(2))*70-b2];
b1 and b2 are vectors (e.g. 5x1)
b1 = [24.1230 24.8000 25.4770 26.1540 26.8310]'
b2 = [67.4820 67.7000 67.9170 68.1340 68.3510]'
and the start point
x0 = [1 -1]
I would find the zero for each pair of b1 and b2, then I expect five pair of solutions. I write
for i=1:length(b1)
fun = @(x) nle(x, b1(i), b2(i));
x = fsolve(fun, x0);
end
Appears five time the statement: Optimization terminated: first-order optimality is less than options.TolFun
but in the workspace only the last solution is stored
x = [0.0965 1.0025]
If I write
for i=1:length(b1)
fun = @(x) nle(x, b1(i), b2(i));
x(i) = fsolve(fun, x0);
end
Optimization terminated: first-order optimality is less than options.TolFun.
??? In an assignment A(I) = B, the number of elements in B and I must be the same.
where is the mistake?
댓글 수: 0
채택된 답변
Daniel Shub
2011년 12월 13일
So close. The statement x(i) is expecting a single value, but you are giving it a row. The statement x(i, :) is expecting a row. Replace
x(i) = fsolve(fun, x0);
with
x(i, :) = fsolve(fun, x0);
You also might want to preallocate x by adding
x = zeros(length(b1), 2);
before your loop. This will allocate memory and can speed things up.
댓글 수: 3
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Get Started with Optimization Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!