How to use ODE 45 to integrate equations of motion?
9 views (last 30 days)
Show older comments
I am modeling a 3d projectile and need help using the ode45 command. I need it to integrate the equations of motion based on my simulation and for it to end when z=0. I need to take this numerical results and sumperimpose them in a plot with my previous data. I need to plot the errors in my data beween my parameter set and this ode 45 set.
This is my code for the simulation
figure('name','Projectile Motion')
xlabel('X (m)')
ylabel('Y (m)')
zlabel('Z (m)')
% This sets the viewing angle
view([1 -1 1])
% This sets the limits on the x- and y-axes
xlim([0,3000])
ylim([0,3000])
zlim([0,1000])
box('on')
grid('on')
hold on
% az is azimuth angle, el is elevation
V0 = 150;
az = 45;
el= 30;
t = [0:0.01:25]';
vx0 = V0*cosd(az)*cosd(el);
vy0 = V0*sind(az)*cosd(el);
vz0 = V0*sind(el);
x = vx0.*t;
y = vy0.*t;
z = vz0*t-0.5*9.81.*t.^2;
[~,ind]=min(abs(z));
plot3(x,y,z)
%Time of flight
T =(2*vz0)/9.81
7 Comments
Answers (1)
Cyrus Tirband
on 28 Oct 2019
First, you need to write down your equations of motion. In your simple case, you have:
with initial conditions
Of course, these integrals are fairly easy to solve and you don't really need to verify these with a numerical solver, but for your assignment you are asked to compare them.
Knowing the equations, the ode function becomes easy to set up. Each of them are independent, and almost the same, so
function dzdt = odefunc(t,z,g)
dzdt = [y(2), -g];
end
similar for x, y (or set g to zero)
then call the solver
[t,z] = ode45(@(t,z), odefunc(t,z,g), [0 tend],[0; vz0]);
The solutions can be seen to overlap perfectly.
2 Comments
Cyrus Tirband
on 29 Oct 2019
The error message is fairly unambiguous. You cannot define functions in the middle of the script, you have to put them at the end.
If you're using MATLAB 2016a or earlier, you'll have to define them in their own file, or make the main script a function.
Additionally, you'll have to define a few parameters before my snippets will generate the solution.
See Also
Categories
Find more on Ordinary Differential Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!