Borrar filtros
Borrar filtros

store solutions of a for loop

1 visualización (últimos 30 días)
gianluca
gianluca el 13 de Dic. de 2011
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?

Respuesta aceptada

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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Get Started with Optimization Toolbox en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by