solving equations initially written as strings using fsolve

Is it possible to solve the following equations that are initially written as string expressions?
eqns={...
'x(1)+x(2)+x(3)+x(4)+x(5)+x(6)+x(7)-1';...
'x(1)-a*x(2)';...
'x(2)-a*x(3)';...
'x(3)-a*x(4)';...
'x(4)-a*x(5)';...
'x(5)-a*x(6)';...
'x(6)-a*x(7)'};
for kk=1:7
myF{kk}=str2func(eqns{kk});
end
funeqns=@(x) myF{:};
a=2;
x0=0.5*ones(1,7);
opts=optimoptions('fsolve','Algorithm','trust-region','TolFun',1e-12,...
'TolX',1e-12,'Display','off');
fs=fsolve(funeqns,x0,opts)';

9 comentarios

Is it possible? Probably. But you need to do significantly more than just call str2func, as for example, this is not a valid function:
str2func(eqns{1})
Warning: The input to STR2FUNC "x(1)+x(2)+x(3)+x(4)+x(5)+x(6)+x(7)-1" is not a valid function name. This will generate an error in a future release.
ans =
function_handle with value:
@x(1)+x(2)+x(3)+x(4)+x(5)+x(6)+x(7)-1
Also, MATLAB will not be able to automatically know that x is a vector of unknowns, but a is apparently something known. You would need to do some of the thinking for MATLAB there. For example, suppose that both a and x are variables in the base workspace.
S H
S H el 29 de Abr. de 2019
Thank you John. What should be done if there are many equations written in different files as expressions. Is there any way to solve them besides rewriting those equations in Matlab command window?
dpb
dpb el 29 de Abr. de 2019
"Any way?" Sure...write a parser for the grammar each of the different files uses for its syntax to convert those to Matlab syntax.
Then, you've got to keep in mind the points John raised regarding what is in present context in workspace, etc., etc., ...
S H
S H el 29 de Abr. de 2019
Thanks.
But why not just use solve()?
S H
S H el 29 de Abr. de 2019
I have found results of fsolve are more reliable than those generated by solve.
Maybe when a closed form solution does not exist, but your equations are linear...
S H
S H el 29 de Abr. de 2019
Exactly.
So solve() should work fine.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Programming en Centro de ayuda y File Exchange.

Preguntada:

S H
el 29 de Abr. de 2019

Comentada:

el 29 de Abr. de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by