How to get a solution involving a symbolic variable with ode45?

I'm trying to work out the maximum horizontal distance that a projectile with air resistance can reach, and the associated launch angle. I currently have a working ODE system that can give the trajectory for the projectile with a given angle using ode45(), that I also have set to stop once it hits the ground again. What I'm having trouble with is getting ode45() to still give me a solution when using a symbolic variable for the angle.
Here is the working code for the projectile:
options = odeset('event',@pjtevent)
pjtode = @(t,y) [y(3); y(4); odefunction([y(3),y(4)])];
v = 100;
theta = pi/4;
[t,y] = ode45(pjtode, [0 25], [0 0 v*cos(theta) v*sin(theta)], options)
pjtevent.m just contains the code to stop the system at the event of it hitting the ground, and odefunction.m is shown below:
function dy = odefunction(x)
K = 0.001;
g = 9.8;
m = 1;
dy = zeros(2,1);
dy(1) = (-K*x(1)^2)/m;
dy(2) = ((-K*x(2)^2)/m)-g;
I thought just setting theta as a symbolic variable would give me a solution depending on theta that I could then optimize, and so tried this:
options = odeset('event',@pjtevent)
pjtode = @(t,y) [y(3); y(4); odefunction([y(3),y(4)])];
v = 100;
syms theta;
[t,y] = ode45(pjtode, [0 25], [0 0 v*cos(theta) v*sin(theta)], options)
However, this returns the following errors:
The following error occurred converting from sym to double:
Error using symengine (line 59)
DOUBLE cannot convert the input expression into a double array.
If the input expression contains a symbolic variable, use VPA.
Error in odefunction (line 6)
dy(1) = (-K*x(1)^2)/m;
Error in @(t,y)[y(3);y(4);odefunction([y(3),y(4)])]
Error in odearguments (line 87)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode45 (line 113)
[neq, tspan, ntspan, next, t0, tfinal, tdir, y0, f0, odeArgs, odeFcn, ...
Any ideas for how to sort this out as I'm having trouble finding how to get it to work? Thanks.

Answers (1)

The ode45 function solves ODEs numerically and will not work with symbolic variables. Take a look at this page from the documentation (note: this is the documentation for the most recent release; if you're using an older release, find the equivalent page in your local documentation) for tools and examples for solving ODEs symbolically.

1 Comment

In addition to what Steve wrote, you might find this example from Global Optimization Toolbox to be relevant.
Alan Weiss
MATLAB mathematical toolbox documentation

Sign in to comment.

Tags

Asked:

on 20 Apr 2016

Commented:

on 14 May 2020

Community Treasure Hunt

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

Start Hunting!