Creating Animations With Octave
Unlike MATLAB, the open source numerical package GNU Octave does not have support for quickly creating animations. That is quite disappointing, because as a physics student, I like to see what the time-dependent equations I solve look like. For example, I am currently taking a course with a section on boundary value problems. This includes the motion of waves on different surfaces, and following their evolution using Fourier series. As you can imagine, that might look quite cool.
Luckily, with the amount of tools available for GNU/Linux, I’ve managed to hack together a quick script that allows me to create AVI movies with Octave that I can then play back. It might not be as simple as MATLAB’s movie() function, but it works! Here is how:
- Create a for loop, with each pass displaying the next frame in the animation.
- Save each frame as an png (or some other type) image such that when the file names are ordered alphabetically, they are also ordered chronologically.
- Use mencoder (or some other encoder) to stitch together the images into a movie file.
- Play the output.avi file to see your animation.
Here is my example of animating the vibrations of a square membrane, that was initially at rest with the displacement of z=x*(1-x)*y*(1-y), but scaled by some constant.
- In your project directory, create an empty directory called output.
- In your project folder, create an Octave script called simulation.m that contains the code for your simulation. For example, my looks like the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
set(0, 'defaultfigurevisible', 'off'); [x,y]=meshgrid([0:0.01:1],[0:0.01:1]); for t=[0:1000] z=x-x; %Initialize empty z grid for nx=[1:10] for ny=[1:10] coeff=(1-(-1)^nx)*(1-(-1)^ny)/(nx^3*ny^3); z=z+coeff*sin(nx*pi.*x).*sin(ny*pi.*y)*cos(sqrt(nx^2+ny^2)*pi*t/100); end end surf(x,y,z); axis([0 1 0 1 -4 4]); shading interp; xlabel("x"); ylabel("y"); zlabel("u(x,y)"); filename=sprintf('output/%05d.png',t); print(filename); end
Some notes of importance in this code:
- Line 1 hides the plot display, so it is not redrawn on the screen every time. This speeds up things considerably.
- Line 19 sets the filename as “#####.png”, a 5 digits frame number. For example, if the frame number is 2, then the filename is 00002.png. This guarantees that the bash shell will order the filenames chronologically.
- Line 20 actually saves the plot to the file
- Run the simulation using octave.
- Stitch together the images into a movie.
mencoder mf://output/*.png -mf w=640:h=480:fps=25:type=png -ovc lavc -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o output.avi
- Watch and enjoy!
Finally, a few other sources that I would recommend to learn more about animation using octave: