7

I am learning matlab myself andI have made an animated plot using matlab;now i want to save it as an video file.can you tell me how to convert my animation into a video file in matlab.Below is my code

x=[1:2];
for i=1:25,
m=randi([3,5]);
n=randi([3,5]);
y=[m n];
bar(x,y)
axis equal                
A(i) = getframe;          
end

matlab version 7.8 R2009a

4 Answers 4

5

use avifile:

aviobj = avifile('example.avi','compression','None');
x=[1:2];
for i=1:25,
m=randi([3,5]);
n=randi([3,5]);
y=[m n];
bar(x,y)
axis equal        
aviobj = addframe(aviobj,gcf);       
drawnow 
end
viobj = close(aviobj)
3
  • hey tanks i tried this script bcoz its look easy..But the video which it made is not of good qualitiy..i cant see my results,its irregular..
    – Eka
    Aug 28, 2012 at 14:44
  • From past experience some player has problem with no compression(VLC). try different player of change compression.Under win32 Cinepak works.
    – Mercury
    Aug 28, 2012 at 20:07
  • 2
    In my Matlab R2014b, avifile is not present anymore: "AVIFILE has been removed. Use VIDEOWRITER instead."
    – Bernhard
    Jun 6, 2016 at 13:45
3

If Matlab's avifile doesn't work (it might have problems with codecs of 64-bit OS), then use mmwrite. http://www.mathworks.com/matlabcentral/fileexchange/15881-mmwrite

It's simple, and it works. I used it to create *.wmv files simply by: mmwrite(filename, frames);

Edit: code example

% set params
fps = 25;
n_samples = 5 * fps;
filename = 'd:/rand.wmv';
% allocate frames struct
fig = figure;
f = getframe(fig);
mov = struct('frames', repmat(f, n_samples, 1), ...
    'times', (1 : n_samples)' / fps, ...
    'width', size(f.cdata, 2), ...
    'height', size(f.cdata, 1));
% generate frames
for k = 1 : n_samples
    imagesc(rand(100), [0, 1]);
    drawnow;
    mov.frames(k) = getframe(fig);
end
% save (assuming mmwrite.m is in the path)
mmwrite(filename, mov);
1

One way to do this is to print the figure to an image, and then stitch the resulting image sequence into a video. ffmpeg and mencoder are great tools for doing this. There are some great resources for describing this if you know the right search terms. I like this one

In mencoder, you could stitch your images together with a command like:

mencoder "mf://*.jpg" -mf fps=10 -o test.avi -ovc lavc -lavcopts vcodec=msmpeg4v2:vbitrate=800
1

Have a look at VideoWriter or see this forum discussion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.