Using fsolve for solving multiple equations by using loops

1 次查看(过去 30 天)
I'm starting to get more deeper into equation solving with Matlab and I'm facing some problems. I have multiple equations stored in Eq (here 13, but later on there will be hundreds):
Eq=
X11 + v1_3/2 + X12*v1_2 - 1
v2_3/2 - 2*X11 + X12*v2_2 + 4
3*X11 + v3_3/2 + X12*v3_2 + 9
X21 + X23*v1_3 + v1_2*(X22 - 1)
X23*v2_3 - 2*X21 + v2_2*(X22 - 2)
3*X21 + X23*v3_3 + v3_2*(X22 + 3)
X32*v1_2 + v1_3*(X33 - 1) + 1/2
X32*v2_2 + v2_3*(X33 - 2) - 1
X32*v3_2 + v3_3*(X33 + 3) + 3/2
Now, I can specify a function as input to fsolve by writing each function by hand, which works:
x0 = ones(1,13);
options = optimoptions('fsolve', 'Algorithm', 'Levenberg-Marquardt');
result = fsolve(@equations, x0, options)
function F = equations(x)
X11=x(1);
X12=x(2);
X21=x(3);
X22=x(4);
X23=x(5);
X32=x(6);
X33=x(7);
v1_2=x(8);
v1_3=x(9);
v2_2=x(10);
v2_3=x(11);
v3_2=x(12);
v3_3=x(13);
F(1) = X11 + v1_3/2 + X12*v1_2 - 1;
F(2) = v2_3/2 - 2*X11 + X12*v2_2 + 4;
F(3) = 3*X11 + v3_3/2 + X12*v3_2 + 9;
F(4) = X21 + X23*v1_3 + v1_2*(X22 - 1);
F(5)=X23*v2_3 - 2*X21 + v2_2*(X22 - 2);
F(6)=3*X21 + X23*v3_3 + v3_2*(X22 + 3);
F(7)= X32*v1_2 + v1_3*(X33 - 1) + 1/2;
F(8)= X32*v2_2 + v2_3*(X33 - 2) - 1;
F(9)= X32*v3_2 + v3_3*(X33 + 3) + 3/2;
end
However, I can't possibly do this for hundreds of equations, so I need to find a way to run a loop. So I thought to first extract all symbolic variables :
allVars=symvar(Eq);
and then run a loop somewhat like this:
x0 = ones(1,13);
options = optimoptions('fsolve', 'Algorithm', 'Levenberg-Marquardt');
result = fsolve(@equations, x0, options)
function F = equations(x,Eq,allVars)
for v=1:length(allVars)
allVars(v)=x(v);
end
for n=1:length(M2)
F(n)=Eq(n);
end
end
This does not work unfortunately. I guess it's because the equations-function needs to have only one input x so that fsolve can handle it. But then I can't assign my equations to F asf.
how could I make this work?

采纳的回答

Matt J
Matt J 2018-12-17
编辑:Matt J 2018-12-17
Use matlabFunction to convert a symbolic implementation of the equations to a numeric one.
  2 个评论
holistic
holistic 2018-12-18
Thank you Matt. That seems to work out well, but gets me into more troubles somehow. After using matlabFunction, I get a function handle of the form:
fun=@(X11,X12...)=...
Trying to input this into fsolve gives me an error:
Failure in initial objective function evaluation. FSOLVE cannot continue.
I assume this is because fsolve wants a function of the form:
fun=@(x) f(x(1)...x(n))
Or maybe I'm doing something wrong.
Matt J
Matt J 2018-12-18
Indeed, you should rewrite your symbolic code so that it works with a matrix of unknowns X(i,j) rather than naming the individual variables Xij.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Solver Outputs and Iterative Display 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by