Using fsolve for solving multiple equations by using loops
19 次查看(过去 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?
0 个评论
采纳的回答
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!