0
votes

I am trying to simulate the trajectories of a few particles in 2D on Matlab. I have the x- and y- coordinates of these particles as a function of time, which I store as matrix x and y. The column in both x and y corresponds to the time, while the row corresponds to the particle number: 1, 2, etc.

I know how to do the animation for one particle with pause, but I am not sure how to customize the code for multiple particles' trajectories. Basically, my idea is that on the initial plot, I have 3 markers which correspond to the initial position of the particles, say particle A, B and C. Then, I would like to follow the movement of these 3 markers, and here is where I encountered the problem: I don't know how to sort the subsequent points according to the particle identity. For example, I want to specify the first point I plot in the second time point as particle A, second point as particle B and third point in particle C.

I have done something similar to this, but in my simulation, the number of particles may be 100, which makes it impractical to create x1, x2, ..., x100, y1, y2, ..., y100 for the animation to work:

y = rand(3, 20); % Generate random sample data.
x = rand(size(y, 1), size(y, 2));
% Now we have x and y sample data and we can begin.
% Extract into separate arrays
x1 = sort(x(1,:));
x2 = sort(x(2,:));
x3 = sort(x(3,:));
y1 = y(1,:);
y2 = y(2,:);
y3 = y(3,:);
for k = 1 : length(x1)
    plot(x1(1:k), y1(1:k), 'r*-', 'LineWidth', 2);
    xlim([min(x(:)), max(x(:))]);
    ylim([min(y(:)), max(y(:))]);
    grid on;
    hold on;
    plot(x2(1:k), y2(1:k), 'g*-', 'LineWidth', 2);
    plot(x3(1:k), y3(1:k), 'b*-', 'LineWidth', 2);
    hold off;
    fprintf('Plotted points 1 through %d\n', k);
    pause(0.8); 
end 

Any ideas or suggestions will be greatly appreciated!

1
Have a look at this answer, it contains an example on how to animate several points simultaneously.Hoki

1 Answers

0
votes

In order to plot all graphs at once, we might make an 2D array.

Below is an example.

y = rand(3, 20); % Generate random sample data.
x = rand(size(y, 1), size(y, 2));
% Now we have x and y sample data and we can begin.
% Extract into separate arrays
x = sort(x');
y=y';

M=size(x);
N=M(2);

for k = 1 : length(x)
    if k==1;

         zeroPad=zeros(1,N);
         x0=[zeroPad;x(1,1:N)];
         y0=[zeroPad;y(1,1:N)];
         plot(x0(1:2,1:N), y0(1:2,1:N), '*', 'LineWidth', 2);

    else
         plot(x(1:k,1:N), y(1:k,1:N), '*-', 'LineWidth', 2); 

    end
    xlim([min(x(:)), max(x(:))]);
    ylim([min(y(:)), max(y(:))]);

    grid on;
    fprintf('Plotted points 1 through %d\n', k);
    pause(0.8); 
end 

One trick was added.

At the first iteration, I added zeros before x and y.

Some unnecessary codes were removed.