store solutions of a for loop

1 回表示 (過去 30 日間)
gianluca
gianluca 2011 年 12 月 13 日
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 Center および File ExchangeGet 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