フィルターのクリア

loop intial guesses in fsolve

3 ビュー (過去 30 日間)
Joon Jeon
Joon Jeon 2012 年 4 月 3 日
I am trying to solve some equations by using solve.
Actually I did it. But this time, I am trying to vary some parameters.
Let's say I have one parameters which is 1:1:9.
And I code it like,
a=1:1:9
for i=1:9
y=@(x) x*exp(a(i))-x/2;
f=@(x) a(i)*x^2+1/2*y(x)-300;
x0=200:-10:110;
p(i)=fsolve(f, x0(i));
end
But it gives me an error message that index matrix is not matching. Is it possible to loop initial guesses in fsolve? (above coding is just an example.)
Since I only use one set of initial guesses in my real model, fsolve keep giving me the same solution.

採用された回答

Matt Tearle
Matt Tearle 2012 年 4 月 3 日
Works for me. Some possible reasons for your error: p is already defined in your workspace, in a way that doesn't allow the assignment you have in the loop; or your "real" code is actually for a function of multiple variables, (so x is actually a vector).
In the first case, that's easily solved by preallocating p before the loop, which you should do anyway:
a=1:1:9;
x0=200:-10:110;
p = zeros(9,1);
for i=1:9
y=@(x) x*exp(a(i))-x/2;
f=@(x) a(i)*x^2+1/2*y(x)-300;
p(i)=fsolve(f, x0(i));
end
plot(a,p,'o-')
In the second case, you'll just need to changing your indexing. x0 would have to be a matrix, as would p, and you'd have to index into a whole row or column (depending on your choice of orientation) on each iteration.

その他の回答 (1 件)

Sean de Wolski
Sean de Wolski 2012 年 4 月 3 日
Copying and pasting what you have above works for me. What do you have for fsolve? IS it being shadowed perhaps?
which -all fsolve

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by