Get dsolve to accept an inputted string?

I am trying to solve an ODE (like dy/dx = 3*exp(-x)-0.4*y), but, it seems that matlab doesn't like me using a sym that was converted from a string. If i replace == equation in line 4 with == 3*exp(-x)-0.4*y (which is what I inputted), then this works. However, I need to accept an inputted equation. So how could I get dsolve to work with a string?
% This works
placeholder = input('Enter ODE -> ','s');
equation = str2sym(placeholder)
syms y(x);
true_equation = diff(y,x) == 3*exp(-x)-(2/5)*y % <-- what I want to change
condition = y(Xo) == Yo
true_equation = dsolve(true_equation,condition)
% This doesn't
placeholder = input('Enter ODE -> ','s');
equation = str2sym(placeholder)
syms y(x);
true_equation = diff(y,x) == equation
condition = y(Xo) == Yo
true_equation = dsolve(true_equation,condition)

 Respuesta aceptada

Walter Roberson
Walter Roberson el 5 de Abr. de 2019

0 votos

Do the str2sym() after the syms y(x)
The syms y(x) defines y as a symbolic function of x. When used in an expression after that such as 3*exp(-x)-0.4*y then it is the symbolic function that gets dropped in, so MATLAB knows that it means 3*exp(-x)-0.4*y(x) . But with your current order of operations, with you not having done the syms y(x) yet, then the str2sym('3*exp(-x)-0.4*y') would assume that x and y are plain scalar variables and so the function y(x) would not get coded in to the str2sym() version.

3 comentarios

Tried this, didn't work, but thanks
% 3*exp(-x)-0.4*y
Xo = 0.15;
Yo = 3;
placeholder = input('Enter ODE -> ','s');
syms y(x);
equation = str2sym(placeholder);
true_equation = diff(y,x) == equation % <-- what I want to change
condition = y(Xo) == Yo
true_equation = dsolve(true_equation,condition)
Xo = 0.15;
Yo = 3;
placeholder = input('Enter ODE -> ', 's');
equation = str2sym(placeholder);
%if the user mentioned y by itself, then y by itself will be
%detected in the equation by symvar and needs to be converted to
%y(x). But if the user mentioned y(something) already, then symvar
%will not pick it up, which is our clue to not change y to y(x).
%for example if the user already wrote y(t) then we would not want
%to end up with y(x)(t)
syms y(x)
vars = symvar(equation);
Y = sym('y');
if ismember(Y, vars)
equation = subs(equation, Y, y);
end
true_equation = diff(y,x) == equation
condition = y(X0) == Yo;
true_equation = dsolve(true_equation, condition);
Logan Trochta
Logan Trochta el 6 de Abr. de 2019
Ok thank you, that worked.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Symbolic Math Toolbox en Centro de ayuda y File Exchange.

Productos

Versión

R2018b

Preguntada:

el 4 de Abr. de 2019

Comentada:

el 6 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