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)

 Accepted Answer

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 Comments

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);
Ok thank you, that worked.

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2018b

Community Treasure Hunt

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

Start Hunting!