Using fsolve in a for loop for multiple equations

8 ビュー (過去 30 日間)
Erwin Fuentes
Erwin Fuentes 2018 年 2 月 9 日
回答済み: Walter Roberson 2018 年 2 月 9 日
Hi I'm using "fsolve" to solve a system of nonlinear equations (really just one of the equations is nonlinear) for the parameters [x,y,z,q]. These parameters must be evaluated each time I change the variable 'a', which is where the for loop comes in. So basically, I'm solving [x,y,z,q] for different values of 'a'. I'm using anonymous syntax functions to solve the equations because it's faster, but my problem is that the code wont run for some reason when I have more than 2 equations. I used the same style from this forum (https://www.mathworks.com/matlabcentral/answers/163622-fsolve-in-a-for-loop) to solve a single equation, but I can't solve this problem when I have more equations.
My code is as follows
clc; clear;
h1 = 0.5;
h2 = 1.25;
gam = 2;
sig = 0.25;
K = 0.025;
D = 5;
a=x1(i);
F = {@(x,q) sig*(a^4-x^4)+h1*(a-x)-q;
@(x,y,q) 1/(1-gam)*(x^(-gam+1)-y^(-gam+1))-q;
@(y,z,q) K*D/(1-gam)*(y^(-gam+1)-z^(-gam+1))-q;
@(z,q) h2*(z-1)-q};
x0 = [1 1 1 1];
xfval(i) = fsolve(F,x0);
end
My error is in the last line which gives me the following:
Error using lsqfcnchk (line 114)
FUN must be a function handle.
Error in fsolve (line 210)
funfcn = lsqfcnchk(FUN,'fsolve',length(varargin),funValCheck,gradflag);
Can anybody help me with this issue? Thanks

回答 (1 件)

Walter Roberson
Walter Roberson 2018 年 2 月 9 日
You cannot pass a cell array of function handles to fsolve.
Also, the handle you pass to fsolve must expect only a single variable (which might be a vector). But you can parameterize:

カテゴリ

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