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)

 채택된 답변

Walter Roberson
Walter Roberson 2019년 4월 5일

0 개 추천

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

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 2019년 4월 6일
Ok thank you, that worked.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기

제품

릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by