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?

采纳的回答

Daniel Shub
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 个评论
gianluca
gianluca 2011-12-13
Can I constrain the solutions between two values (e.g. 0 and 1)?
Daniel Shub
Daniel Shub 2011-12-13
You should ask that as a new question.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile 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!

Translated by