我在使用fsolve函数解决Matlab中的一组5个方程时遇到了困难。
以下是5个等式:
y = a + d + e
y + x = c + d + 2e
2x = 4a + 2b + 2c
k1 =(d * b ^ 3 /(a * c))*((P / Pref)/(a + b + c + d + e))^ 2
k2 = b e /(d c)
y,x,k1,k2,P,Pref是我设置的所有参数,但是希望将它们保留在函数中,以便我可以在代码中快速更改它们以找到新的答案。 a,b,c,d,e是我想要解决的变量(它们是反应平衡方程的组成)
我试图对函数中的参数进行硬编码,但这不起作用。我只是不确定该怎么做。我改变的每件事都会产生新的错误。最常见的是数据类型必须是“双”。
编辑:添加代码
首先是功能:
function F = myfun(Q,I)
a = Q(1);
b = Q(2);
c = Q(3);
d = Q(4);
e = Q(5);
x = I(1);
y = I(2);
k1 = I(3);
k2 = I(4);
P = I(5);
Pref = I(6);
F(1) = a + d + e - y;
F(2) = c + d + 2*e - y - x;
F(3) = 4*a + 2*b + 2*c - 2*x;
F(4) = ((d * b^3)/(a*c))*((P/Pref)/(a+b+c+d+e))^2 - k1;
F(5) = (b*e)/(c*d);
接下来是该计划:
%Q = [a,b,c,d,e]
%I = [x,y,k1,k2,P,Pref]
%The values for the inputs will be changed to vary the output
%Inputs:
x=5;
y=1;
k1=5;
Pref=1;
P=1;
k2=-0.01;
syms K
k1 = solve(log10(k1) - k1);
syms L
k2 = solve(log10(k2) - k2);
x = double(x);
y = double(y);
Pref = double(Pref);
P = double(P);
k1 = double(k1);
k2 = double(k2);
%Solving:
I = [x,y,k1,k2,P,Pref];
q = [0,0,0,0,0]; %initial guess
Q = fsolve(@myfun,[q,I])
当我运行时,会出现这些错误:
Error using myfun (line 7)
Not enough input arguments.
Error in fsolve (line 218)
fuser = feval(funfcn{3},x,varargin{:});
Error in Coal (line 27)
Q = fsolve(@myfun,[q,I])
Caused by:
Failure in initial user-supplied objective function evaluation. FSOLVE cannot continue.
编辑2:更改了fsolve行,但仍然出现错误:
Error using trustnleqn (line 28)
Objective function is returning undefined values at initial point. FSOLVE cannot continue.
Error in fsolve (line 376)
[x,FVAL,JACOB,EXITFLAG,OUTPUT,msgData]=...
Error in Coal (line 27)
fsolve(@(q) myfun(q,I),q)
Edit3:更改了几个参数和最初的猜测,我现在得到了答案,但它也提出了这个:
Solver stopped prematurely.
fsolve stopped because it exceeded the function evaluation limit,
options.MaxFunEvals = 500 (the default value).
ans =
0.0000 2.2174 3.7473 1.4401 3.8845
如何让它不能过早停止?
答案 0 :(得分:0)
Re:我怎么能让它不能过早停止?
在您对fsolve的调用中传递非默认选项。
在这里参考签名,fsolve(myfun,q,options), http://www.mathworks.com/help/optim/ug/fsolve.html
阅读有关使用optimoptions创建选项的信息, http://www.mathworks.com/help/optim/ug/optimoptions.html
你应该能够通过提高TolFun和TolX等收敛标准的值来“不要过早地停止”。
但是,建议您阅读您依赖的基础算法来执行此数值解决方案, (编辑:我试图修复非链接链接,但我不允许提供超过两个... Boo)www.mathworks.com/help/optim/ug/fsolve.html#moreabout
您收到的错误只表示在进行500次函数评估后,算法尚未收敛于符合默认求解器选项的可接受解决方案。仅增加MaxFunEvals可以允许算法额外迭代以在默认容差内收敛。例如,
options = optimoptions('MaxFunEvals',1000); % try something bigger than 500
fsolve(@(q) myfun(q,I),q,options);