Using fsolve in a for loop for multiple equations
8 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
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:
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!