Rick T
Rick T

Reputation: 3389

animate plot / trajectory in matlab / octave

I'm trying to animate this spiral using matlab / octave I want it to spiral up or down

t = 0:0.1:10*pi;
r = linspace (0, 1, numel (t));
z = linspace (0, 1, numel (t));
plot3 (r.*sin(t), r.*cos(t), z);

spiral

I tried using a for loop to animate it but that just gives me a cone shape see code and image below

clear all, clc,clf,tic
t = 0:0.1:10*pi;
r = linspace (0, 1, numel (t));
z = linspace (0, 1, numel (t));

for ii=1:length(r)
    ii
    plot3 (r.*sin(t(ii)), r.*cos(t(ii)), z);
    hold on
    %pause (.00001)
end

Image enter image description here

Upvotes: 5

Views: 19886

Answers (4)

David Contreras
David Contreras

Reputation: 236

This is not the trajectory solution, but here is a spinning tornado.

phi = linspace(0, 10*pi, 300);
r = linspace (0, 1, 300);
z = linspace (0, 1, 300);
s = 100; %speed of turning
for t = 0:0.01:10 %t is time
  plot3 (r.*sin(phi+t*s), r.*cos(phi+t*s), z);
  pause(0.01)
end

Upvotes: 1

Assad Ebrahim
Assad Ebrahim

Reputation: 6361

You could also use the comet3() package, which animates the trajectory through the plot:

delay = 0.001  % seconds
figure
comet3(r.*sin(t), r.*cos(t), z, delay);

This animates a continuous trajectory which I prefer over a discrete sequence of *'s.

The one downside is that the version of comet and comet3 that shipped with Octave 3.6.4 are slow, regardless of the delay you use. But this can be overcome by using the following trick courtesy of andyras in this SO question:

% plot the first point to get started
h = plot3(x(1),y(1),z(1),"b");
axis([min(x), max(x), min(y), max(y), min(z), max(z)]);

% refresh the plot in a loop through the rest of the data
for k = 1:length(z);
   set(h, 'XData', x(1:k));
   set(h, 'YData', y(1:k));
   set(h, 'ZData', z(1:k));
   pause (0.001); % delay in seconds
       % alternatively could provide a velocity function
       % pause(sqrt(vx(k)^2+vy(k)^2+vz(k)^2));  
endfor

Minor note: once you've modified the function, you'll need to force Octave to reload it as it won't do this by default. You can either restart, or better yet use clear comet and clear comet3. Then the next time those functions are called, their definitions will be refreshed.

Upvotes: 4

am304
am304

Reputation: 13876

The following appears to work in Octave 3.6.2

t = 0:0.1:10*pi;
r = linspace (0, 1, numel (t));
z = linspace (0, 1, numel (t));

figure
axis([-1 1 -1 1 0 1])
hold on

for ii=1:length(r)
    plot3 (r(ii)*sin(t(ii)), r(ii)*cos(t(ii)), z(ii),'*');
    pause (.001)
end

Upvotes: 2

davin
davin

Reputation: 45525

Certainly not the prettiest, but these are the first changes you need to make to your code for it to do something close to what you want.

t = 0:0.1:10*pi;
z = linspace (1, 0, numel (t));
for ii=1:length(t)
    plot3 (z(ii)*sin(t(ii)),z(ii)*cos(t(ii)), z(ii));
    hold on
    pause (.00001)
end

Upvotes: 1

Related Questions