Make a 3D animation of a system of equations in R^3.

1 view (last 30 days)
I have variables x, y, z and I want to model an object's position in 3D space based on a system of differential equations which is dependent on time. I have dx/dt= -y-z , dy/dt= x+y , dz/dt= 1+xz
and initial conditions are its at (1,2,5) say . How do I make a model of this motion as time passes on Matlab?
Thanks

Accepted Answer

arich82
arich82 on 2 Oct 2015
It partly depends on what exactly you want. A quick and dirty approach would be to solve the ODE over a fixed interval using ode45, and plot the results:
t = 0:0.001:5;
y0 = [1; 2; 5];
f = @(t, y) [-y(2) - y(3); y(1) + y(2); 1 + y(1)*y(3)];
[~, y] = ode45(f, t, y0);
figure;
comet3(y(:, 1), y(:, 2), y(:, 3));
If you want to plot the results as you incrementally solve the equation, you can use the techniques described in the FAQ or the notes on animation, but you'd have to be careful to ensure that the ODE is well suited to an explicit integration scheme, and that your step size is appropriate:
f = @(t, y) [-y(2) - y(3); y(1) + y(2); 1 + y(1)*y(3)];
y0 = [1; 2; 5];
t0 = 0;
hf = figure;
ha = axes;
hp = plot3(ha, NaN, NaN, NaN, '.', 'MarkerSize', 50);
ht = title('t = ');
set(ha, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual');
set(ha, 'XLim', [-20, 20], 'YLim', [-90, 10], 'ZLim', [-50, 200]);
dt = 0.001;
tmax = 5;
t = t0;
y = y0;
while t < tmax
t = t + dt;
dy = f(t, y)*dt;
y = y + dy;
set(hp, 'XData', y(1), 'YData', y(2), 'ZData', y(3));
set(ht, 'String', ['t = ', num2str(t, '%5.3f')]);
drawnow;
end
Using one of the ODE solvers is definitely safer, if you care at all about the accuracy of the results...

More Answers (1)

Steven Lord
Steven Lord on 2 Oct 2015
Take a look at the ODE solvers like ODE45 and the description of the OutputFcn option you can specify using ODESET.
  1 Comment
arich82
arich82 on 2 Oct 2015
I was definitely unaware of the OutputFcn in odeset (likewise for @odeplot).

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!