1

I am trying to write a simple n-body gravity simulation with 4 particles in C++. I am outputting the positions of the 4 particles to .mat files labeled "time_X.mat" (where X=1,2,3.... indicates the time-stamp) in the form of a 4x2 matrix where i'th row indicates (x,y) cooridinates of the ith particle at time X .

Now for a particular time-step I am able load the .mat file into MATLAB and get a scatterplot of the points in the matrix, showing me particle positions. But I would like to create a movie out of all the .mat files / scatter-plots of the time_X.mat files which shows me the evolution of the 4 particle syestem . How should I do that in MATLAB?

smilingbuddha
  • 14,334
  • 33
  • 112
  • 189

1 Answers1

0

First you have to make frames (images) of each time step of your simulation.

Since you have Cartesian coordinates, you have to convert your x and y coordinates to pixel indices, and make an image matrix from them. See my answer to a relevant question for an example of how to do this. You could also modify the code to make your points larger than a pixel, have shapes, etc., perhaps with strel or [a,b,~] = sphere(N).

Once you have the frames, you can easily make an AVI file (uncompressed or MPEG) in MATLAB:

aviOutput = fullfile('path','to','file.avi');
aviobj = VideoWriter(aviOutput);
aviobj.Quality = 100;
aviobj.FrameRate = 24; %# arbitrary
open(aviobj);
for i=1:length(frames)
    writeVideo(aviobj,frames{i}); %# or frames(:,:,i) etc.
end
close(aviobj);

Update

The above assumes the time steps are all available. For example:

files = dir('path/to/dir');
files(1:2) = []; %# . and ..
orderedfiles = cell(length(files),1);
for i=1:length(files)
   ind = sscanf(files(i).name,[name '%*[_]%u%*s']);
   orderedfiles{ind+1} = files(i).name;
end
timeSteps = zeros(numPoints,2,length(orderedfiles));
for i=1:length(orderedfiles)
    temp = load(orderedfiles(i).name);
    timeSteps(:,:,i) = temp.matrixName %# All the same name?
end

The code from the linked answer is written to operate on two vectors x and y with the coordinates, which you would get with timeSteps(:,1,i) and timeSteps(:,2,i), and do for each time step.

Community
  • 1
  • 1
reve_etrange
  • 2,561
  • 1
  • 22
  • 36