1
votes

I'm using MATLAB R2016b - student edition to develop an m-file which takes as input a symbolic differential equation, f(t,y), and outputs a slope field and solution curve based on an initial condition. The code is

prompt={'dy/dt =','tspan','y0 ='};
title='Slope Field Calculator'; 
answer=inputdlg(prompt,title);
tspan = str2num(answer{2}); %#ok<*ST2NM>
y0 = str2double(answer{3});
syms t y
f = symfun(sym(answer{1}),[t,y]);
[t,y] = ode45(f, tspan, y0);
hold on
dirfield(f,-5:.3:5,-5,.3:5)
plot(t,y,'b','LineWidth',2)

The dirfield(f,-5:.3:5,-5:.3:5) function has input f as an @ function, or an inline function, or the name of an m-file with quotes. The dirfield function then plots a direction field for a first order ODE of the form y' = f(t,y) using t-values from t1 to t2 with spacing of dt and using y-values from y1 to y2 with spacing of dy.

According to MATLAB help, the ode45 function solves differential equations. [TOUT,YOUT] = ode45(ODEFUN,TSPAN,Y0) with TSPAN = [T0 TFINAL] then integrates the differential equation y' = f(t,y) from time T0 to TFINAL with initial conditions Y0. The input ODEFUN is a function handle. For a scalar T and a vector Y, ODEFUN(T,Y) must return a column vector corresponding to f(t,y).

When I run the code, the dialogue box runs nicely and accepts my inputs. But when I click "OK", the code throws this error:

Warning: Support of character vectors that are not valid variable names or 
define a number will be removed in a
future release. To create symbolic expressions, first create symbolic 
variables and then use operations on them. 
> In sym>convertExpression (line 1559)
  In sym>convertChar (line 1464)
  In sym>tomupad (line 1216)
  In sym (line 179)
  In SlopeFieldsSolutionCurves (line 9) 
Undefined function 'exist' for input arguments of type 'symfun'.

Error in odearguments (line 59)
  if (exist(ode)==2)

Error in ode45 (line 115)
    odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, 
varargin);

Error in SlopeFieldsSolutionCurves (line 10)
[t,y] = ode45(f, tspan, y0);

Where am I going wrong?

1

1 Answers

1
votes

ode45 takes a function handle, not a symbolic function. Use matlabFunction instead:

[t,y] = ode45(matlabFunction(f), tspan, y0);

To get rid of the first warning, you need to define f a bit differently:

f = evalin( symengine, answer{1} );
f = symfun( f, [t,y] );