Creating Simple Animation in MATLAB with Timer Object

Goals

In this tutorial, you will learn how to create a simple animation by taking advantage of MATLAB’s built-in timer object.

Conditions and Assumption

This tutorial was made based on MATLAB R2011b on Win7 64bit operating system. In this tutorial, it is assumed that you are using the same version of MATLAB and you have basic understanding and familiarity of MATLAB and its basic built-in functions (for the explanation of basic MATLAB’s built-in function, see MATLAB’s online documentation site). It is also assumed that you understand programming flow control such as conditional statements (switchcase and ifelse) and loops (while and for).

Since this tutorial was made as the continuation of the previous Creating Simple Animation in MATLAB tutorial, it is also assumed that you already have the basic concept of creating animation in MATLAB and/or have read the Creating Simple Animation in MATLAB tutorial. Some reference to the previous tutorial was also used in this tutorial, thus, it is recommended to read Creating Simple Animation in MATLAB tutorial first before you proceed with this tutorial.

1. Concept of MATLAB’s Timer Object

Timer object is a MATLAB object that is used to run a certain function/task numerous times with a certain schedule (for complete explanation of MATLAB’s timer object, see MATLAB’s online documentation site). By setting it up properly, timer object can be used to create an animation. The main advantage of using timer object to run animation is that it eliminates the need to use while loop to update the animation and eliminates the need to use pause command to control the animation speed. The elimination of while loop will make it easier to design an escape from infinite loop while the elimination of pause command will enable user to interact with other MATLAB’s component such as the command window while the animation is being played.

In all example codes used in Creating Simple Animation in MATLAB tutorial, pause command is used at the end of every loop. The purpose of pause command is used to allow MATLAB to redraw the animation and to control the pace of the animation (by instructing MATLAB to wait a certain time before executing the next loop and updating the animation). Unfortunately, pause command puts MATLAB into sleep state and rendering MATLAB unable to do anything else during the waiting time between animation update. This is why MATLAB command window is blocked and keep showing busy status while the animation is being played.

By using timer object, the execution of MATLAB code for animation update can be scheduled automatically with a certain execution rate or time delay between each execution, thus, rendering pause command unnecessary. This way, MATLAB is kept idle/alive/awake during the waiting time in between animation update, allowing MATLAB to execute other commands (from command window or other functions). Nevertheless, keep in mind that while this may make MATLAB seems to be able to execute two tasks at the same time, MATLAB is actually a single threaded application (simply said, it can only do one job at one time). When two tasks are requested at the same time, MATLAB will execute one first and queue the other one. Thus, executing a command during this waiting time may disturb or cause lag/delay in the animation.

To use timer object to perform a certain task continuously and periodically, timer object must be created first with timer command. Then, said task must be assigned as the TimerFcn callback function of the timer object. Assigning certain task as the TimerFcn can be done in two ways. The first one is by re-writing said task as string and passing these strings to TimerFcn (similar with eval function). The other way is to write said task as a function and passing the function handle to TimerFcn. Passing string as callback function is pretty simple and straight forward, as if you are re-typing what you want to be executed. However, this will get complicated if the callback content is long and complicated. When that is the case, it is preferred to pass the function handle to TimerFcn instead of command string. Passing function handle is done by using @ followed by the function name (NOT the file name of the function that contains it). This procedure is similar with assigning DeleteFcn on figure object that is shown in the previous Creating Simple Animation in MATLAB tutorial. Note that the function that are assigned as the TimerFcn should be declared with at least two input arguments (source and event data) as it is required by MATLAB for typical declaration of callback function.

Besides TimerFcn, the timer object’s properties must be appropriately set in order to execute the task as desired. Three critical properties that should be set properly are ExecutionMode, Period, and TaskToExecute. By default (when it is not set during object creation), ExecutionMode is set to ‘singleShot’, where the TimerFcn will only be executed once. This property must be set to either ‘fixedRate’, ‘fixedDelay’, or ‘fixedSpacing’ so that the timer object executes the TimerFcn multiple times. Period property should be set to the desired waiting time / delay between the executions of TimerFcn. Note that the definition of waiting time / delay differs for each ExecutionMode (for complete explanation of MATLAB’s timer object and its properties, see MATLAB’s online documentation site). On the other hand, TaskToExecute should be set to the desired number of times the TimerFcn to be executed. TaskToExecute can be assigned to either a finite number or to Inf to make timer object keep on re-executing TimerFcn until it is told to stop.

After assigning TimerFcn and setting object properties, start command must be used to invoke the timer object to start executing TimerFcn as scheduled. Since start command requires timer’s object identifier as its input argument, timer object must always be assigned to a variable when it is created. After start command is invoked, timer object will execute TimerFcn periodically as scheduled until number of execution stated in TaskToExecute is achieved or stop command is invoked. If TaskToExecute is set to Inf, timer object will keep on executing TimerFcn until the stop command is invoked. Similar to start command, stop command also requires the timer object’s identifier as its input argument.

The following Script02a shows a simple example of using timer object to execute a task periodically. In this example, timer object is created and it is assigned to variable t (line 12 to 17). Note that the TimerFunction callback is defined with string instead of function handle (line 13). This means that TimerFcn will run the string commands as if it is typed directly in command window. On the other hand, ExecutionMode is set to ‘fixedRate’ and Period to 1. This means that the t timer object will execute TimerFcn with delay of 1 second between the start of two consecutive executions. When this script is executed, MATLAB will display ‘Hello! How are you?’ string along with a random number (to give distinction between each message) every one second to the command window. Since TasksToExecute property is set to Inf, MATLAB will keep displaying new messages every one second until stop(t) command is invoked. Notice that when MATLAB is running the script, the command window is not blocked and is able to accept any command given to it. Any command can be given to MATLAB and MATLAB will respond to it despite the fact that it also currently running the TimerFcn.

%--------------------------------------------------------------------------
%Script02a - Shouter
%Creating Simple Animation in MATLAB with Timer Object
%MATLAB undercover
%zerocrossraptor.wordpress.com
%--------------------------------------------------------------------------
%This script m-file displays 'How Are You' message to command window every
%one second.
%--------------------------------------------------------------------------

%CodeStart-----------------------------------------------------------------
%Creating timer object
    t=timer('TimerFcn',['disp([''Hello! How Are you? - '',',...
                        'num2str(rand)])'],...
            'ExecutionMode','fixedDelay',...
            'Period',1,...
            'TasksToExecute',Inf);
%Executing timer function
    start(t);
%Waiting for 10 seconds
    %pause(10);
%Stopping timer function execution
    %stop(t);
%CodeEnd-------------------------------------------------------------------

2. Creating Animation with Timer Object

Creating animation with timer object is done with the same concept as creating animation without timer object (with while loop). It is done by creating a plot and continuously updating it periodically. However, when using timer object, the updater part of the code is assigned as the TimerFcn callback function instead of being put inside the while loop. While axis manipulation command must still be included inside the TimerFcn callback function (to maintain axis configuration throughout the animation), pause command must not be included as it is unnecessary and will mess up the execution timing. As for the timer object’s properties itself, ExecutionMode property is usually set to ‘fixedRate’ (to ensure consistent animation pace) while TaskToExecute property is set to Inf. For Period property, its value must be tweaked and adjusted appropriately to ensure smooth animation. To understand these concepts, see Script02b below (Note that Script02b creates the exact same sinus animation as Script01a from the previous Creating Simple Animation in Matlab tutorial does, only it is re-written with timer object).

%--------------------------------------------------------------------------
%Script01a - Dancing Sinus
%Creating Simple Animation in MATLAB with Timer Object
%MATLAB undercover
%zerocrossraptor.wordpress.com
%--------------------------------------------------------------------------
%This script m-file creates an endless animation of sinusoidal wave whose
%amplitude keeps on changing between -1 and 1 by using timer object.
%--------------------------------------------------------------------------

%CodeStart-----------------------------------------------------------------
%Creating base plot (sinusoidal plot)
    x=0:10:360;
    y=sind(x);
%Declaring variable as a scale factor for base plot
    theta=0;
%Creating timer object
    t=timer('TimerFcn',['theta=theta+1;',...
                        'plot(x,y*sind(theta));',...
                        'axis([0,360,-1.2,1.2])'],...
            'ExecutionMode','fixedDelay',...
            'Period',0.1,...
            'TasksToExecute',Inf);
%Executing timer function
    start(t);
%CodeEnd-------------------------------------------------------------------

As in Script01a from the previous Creating Simple Animation in Matlab tutorial, Script02b above also generates an animation of sinusoidal wave with varying amplitude. The script is initiated with some variable declaration to create basic sinus plot (line 12 to 14). This part is exactly the same with Script01a from the previous Creating Simple Animation in Matlab tutorial. However, the initialization is then followed by declaration of t timer object (line 17 to 23) instead of while loop. Notice that the content of TimerFcn is the string form of line 24 to 26 (the content of main while loop) of Script01a from the previous Creating Simple Animation in Matlab tutorial. The pause command is not included here as it is unnecessary. After t timer object is created, start(t) command is invoked to start the execution of TimerFcn callback function, hence, starting the animation. Keep in mind that since TasksToExecute is set to Inf, t timer object will keep on executing it TimerFcn until stop(t) is invoked . In this case, pressing ctrl+C sometimes may not stop the timer object because it may be pressed when MATLAB thread is not doing anything (idle) during the waiting time between two consecutive executions of TimerFcn.

3. Using Function Handle as TimerFcn and Wrapping All Necessities in One File

In Script02b, the TimerFcn is set by passing command string to it. While this does the job well for the sinus wave animation, it is not the best way of using timer object. It will get more complicated as the content gets longer and will limit the functionality of TimerFcn itself. Thus, it is always preferred to pass function handle to TimerFcn instead of command string. To pass function handle to TimerFcn, the callback function itself must be defined first. Since this callback function is most likely to be exclusive and will not be share-used by other timer object, it should be put together in one m-file with the main code. In order to do so, the main code must be written as function m-file or class m-file instead of script m-file (as stated in section 4 of the previous Creating Simple Animation in MATLAB tutorial). This way, the callback function can be written as local function and contained within the same file.

The following TBouncingBallFunction m-file below shows the example of wrapping timer object inside a function m-file. This m-file is created by modifying BouncingBallFunction in the previous Creating Simple Animation in MATLAB and also creates an animation of bouncing ball. However, timer object is used in this function instead of while loop. Similar to the previous BouncingBallFunction, TBouncingBallFunction is started by declaring all the necessary variables (line 14 to 32). However, in TBouncingBallFunction, variable declarations are followed by the declaration of timer object, anim, in line 34 to 37. In this declaration, @runanimationfcn is passed to TimerFcn (line 34) as the callback function handle. Then, start command is invoked to start the execution of runanimationfcn (TimerFcn) by timer object anim, which then leads to the start of animation. The TimerFcn callback function itself, runanimationfcn, is declared as local function in line 43 to 57. Notice that the content of runanimationfcn is the content of the while loop in BouncingBallFunction (line 37 to 54) without tic, toc, and pause command. These commands are deprecated because the timer object will automatically handle the execution schedule based on given timer object’s properties set in line 34 to 37.

function TBouncingBallFunction

%--------------------------------------------------------------------------
%TBouncingBallFunction
%Creating Simple Animation in MATLAB
%MATLAB Undercover
%zerocrossraptor.wordpress.com
%--------------------------------------------------------------------------
%This function m-file creates an endless animation of bouncing ball by
%using timer object.
%--------------------------------------------------------------------------

%CodeStart-----------------------------------------------------------------
%Declaring ball's initial condition
    initpos=50;     %Ball's initial vertical position
    initvel=0;      %Ball's initial vertical velocity
%Declaring environmental variable
    r_ball=5;       %Ball's radius
    gravity=10;     %Gravity's acceleration
    c_bounce=1;     %Bouncing's coefficient of elasticity
%Declaring animation timestep
    dt=0.012;       %Animation timestep
%Initiating figure, axes, and objects for animation
    fig=figure('DeleteFcn',@closefigurefcn);
    axs=axes('Parent',fig);
    ball=rectangle('Position',[-r_ball,initpos,r_ball,r_ball],...
                   'Curvature',[1,1],...
                   'FaceColor','b',...
                   'Parent',axs);
    line([-5*r_ball,5*r_ball],...
         [0,0],...
         'Parent',axs);
%Creating timer object
    anim=timer('TimerFcn',@runanimationfcn,...
               'ExecutionMode','fixedRate',...
               'Period',dt,...
               'TasksToExecute',Inf);
%Initiating ball's position and velocity
    pos=initpos-r_ball;             %Ball's current vertical position
    vel=initvel;                    %Ball's current vertical velocity
%Starting animation
    start(anim);
%Declaring callback function to play animation
    function runanimationfcn(source,event)
        %Updating ball's position and velocity
        pos=pos+(vel*dt);
        vel=vel-(gravity*dt);
        if pos<0
            vel=-vel*c_bounce;
        end
        %Updating ball
        set(ball,'Position',[-r_ball,pos,r_ball,r_ball]);
        %Preserving axes
        axis(axs,[-5*r_ball,5*r_ball,0,initpos+2*r_ball]);
        axis(axs,'equal');
        axis(axs,'off');
    end
%Declaring callback function to end animation
    function closefigurefcn(source,event)
        stop(anim);
        delete(anim);
    end
%CodeEnd-------------------------------------------------------------------

end

Besides the main code itself, it should be notice that TBouncingBallFunction uses different commands to escape the infinite loop and stops the animation after the figure is closed. Instead of setting play variable to false like in BouncingBallFunction, in TBouncingBallFunction, stop command is invoked (line 60) to stop the timer object anim from re-executing runanimationfcn. In this case, pause command is unnecessary because the timer object anim will automatically handle the execution termination. Instead, delete command is used in line 61 to delete the timer object. While the code itself can still run even though this line is commented out, it is always a good practice to clear any unused object to release any system resources. This is also done to prevent error that may arise when an object is still exist on memory, but MATLAB has no reference/pointer to it.

The following TBouncingBallClass_A m-file below shows the example of wrapping timer object inside a class m-file. This m-file is created by modifying BouncingBallClass in the previous Creating Simple Animation in MATLAB and also creates an animation of bouncing ball. In this m-file, the class constructor begins with variable declarations (line 41 to 54), which is just a copy of line 42 to 55 of the previous BouncingBallClass, followed by the declaration of timer object anim (line 56 to 60) and start command to start the animation. Lastly, to stop the animation when the figure is closed, both stop and delete command are used as in TBouncingBallFunction. Notice that in this class m-file, the function handle for TimerFcn is passed differently than what is done in TBouncingBallFunction m-file. This is done because in this case, runanimationfcn stands as one of the TBouncingBallClass_A‘s class method instead of a simple local function. Thus, the argument passed to TimerFcn must also includes this, src, and event as the input argument for runanimationfcn.

classdef TBouncingBallClass_A<handle

%--------------------------------------------------------------------------
%BouncingBall (Class with Timer Object)
%Version 1.00
%Created by Stepen
%--------------------------------------------------------------------------
%This class m-file creates an endless animation of bouncing ball by
%using timer object.
%--------------------------------------------------------------------------

%CodeStart-----------------------------------------------------------------
%Declaring class constants
properties(Constant)
    %Declaring environmental variable
    r_ball=5;       %Ball's radius
    gravity=10;     %Gravity's acceleration
    c_bounce=1;     %Bouncing's coefficient of elasticity
    %Declaring ball's initial condition
    initpos=50;     %Ball's initial vertical position
    initvel=0;      %Ball's initial vertical velocity
    %Declaring time step
    dt=0.012;       %Animation timestep
end
%Declaring class properties
properties
    %Declaring variables for figure, axes, and plot objects
    fig;        %Class' figure handle
    axs;        %Class' axes handle
    ball;       %Class' rectangle object for ball
    ground;     %Class' line object for ground
    %Declaring variable for animation
    anim;       %Class' timer object
    pos;        %Ball's current vertical position
    vel;        %Ball's current vertical velocity
end
%Declaring class method
methods
    %Declaring constructor
    function this=TBouncingBallClass_A()
        %Initiating GUI figure, axes, and objects for animation
        this.fig=figure('DeleteFcn',@(src,event)closefigurefcn(this));
        this.axs=axes('Parent',this.fig);
        this.ball=rectangle('Position',[-TBouncingBallClass_A.r_ball,...
                                        TBouncingBallClass_A.initpos,...
                                        TBouncingBallClass_A.r_ball,...
                                        TBouncingBallClass_A.r_ball],...
                            'Curvature',[1,1],...
                            'FaceColor','b',...
                            'Parent',this.axs);
        this.ground=line([-5*TBouncingBallClass_A.r_ball,...
                          5*TBouncingBallClass_A.r_ball],...
                         [0,0],...
                         'Parent',this.axs);
        %Creating timer object
        this.anim=timer('TimerFcn',@(src,event)...
                                     runanimationfcn(this,src,event),...
                        'ExecutionMode','fixedRate',...
                        'Period',TBouncingBallClass_A.dt,...
                        'TasksToExecute',Inf);
        %Initiating ball's position and velocity
        this.pos=TBouncingBallClass_A.initpos-TBouncingBallClass_A.r_ball;
        this.vel=TBouncingBallClass_A.initvel;
        %Starting animation
        start(this.anim);
    end
    %Declaring callback function to run the animation
    function runanimationfcn(this,src,event)
        %Updating ball's position and velocity
        this.pos = this.pos+(this.vel*TBouncingBallClass_A.dt);
        this.vel = this.vel-...
                   (TBouncingBallClass_A.gravity*TBouncingBallClass_A.dt);
        if this.pos<0
            this.vel = -this.vel*TBouncingBallClass_A.c_bounce;
        end
        %Updating ball
        set(this.ball,'Position',[-TBouncingBallClass_A.r_ball,...
                                  this.pos,...
                                  TBouncingBallClass_A.r_ball,...
                                  TBouncingBallClass_A.r_ball]);
        %Preserving axes
        axis(this.axs,[-5*TBouncingBallClass_A.r_ball,...
                       5*TBouncingBallClass_A.r_ball,...
                       0,...
                       TBouncingBallClass_A.initpos+...
                       2*TBouncingBallClass_A.r_ball]);
        axis(this.axs,'equal');
        axis(this.axs,'off');
    end
    %Declaring callback function to end animation
    function closefigurefcn(this)
        stop(this.anim);
        delete(this.anim);
        pause(1);
    end
end
%CodeEnd-------------------------------------------------------------------

end

4. Modifying Animation when It Is Being Played

It was stated previously in the beginning of this tutorial that using timer object allows user to interact with MATLAB’s command window while the animation is being played because pause command is not used to put MATLAB into sleep state. While this seems trivial, actually, this feature allows the animation to be altered while the animation itself is being run. With this concept, an animation can be made into a game or at least to respond to user interaction. Unfortunately, since function m-file does not create any object in MATLAB workspace which can be altered from command window, this concept only apply when the animation is written as class m-file. However, it does not mean that function m-file cannot be used to create any game or animation that interacts with user. By taking advantage of figure object’s callback function, user-interaction feature can be achieved. However, this section will only focus on altering animation from command window which can be achieved only when the animation is written as class m-file (For tutorial on user interaction with figure objects, see my other tutorial, Creating Simple User Interactive Animation in MATLAB *ToBeAdded*).

To accommodate user-invoked command from command window, TBouncingBallClass_A must be slightly altered. First, the start command written in line 65 should be removed. Doing so will cause the animation not to be played directly after the object is created or when run button (F5) is pressed. Instead, a new public method is added just to start the animation. The advantage of doing this is to allow user to alter the animation parameters before it is played and to allow the animation to be re-played without creating new objects. As the counterpart, another public method should also be added to stop the animation.

The following code shows the content of TBouncingBallClass_A after being altered to accomodate user-interaction. In this new code, public method start (line 98 to 100) and stop (line 102 to 104) is added, allowing user to start and stop the animation without closing the figure (because closing the figure will cause the animation object to be deleted). Aside from that, a new public method, putBallAt is also added to allow user to alter the ball’s position and velocity. This method is the one that user can use to alter the animation while it is being played. Notice also that in this code, fig figure object is created by assigning its WindowStyle to ‘docked’. Doing so will dock the created figure window with the main MATLAB desktop. This was done so that the command window and the animation can be seen together at the same time (assuming that the command window is also docked into MATLAB’s desktop). Keep in mind that depending on your own MATLAB desktop configuration, this may yield different result.

classdef TBouncingBallClass_B<handle

%--------------------------------------------------------------------------
%TBouncingBallFunction
%Creating Simple Animation in MATLAB with Timer Object
%MATLAB Undercover
%zerocrossraptor.wordpress.com
%--------------------------------------------------------------------------
%This class m-file creates an endless animation of bouncing ball by using
%timer object.
%--------------------------------------------------------------------------

%CodeStart-----------------------------------------------------------------
%Declaring class constants
properties(Constant)
    %Declaring environmental variable
    gravity=10;     %Gravity's acceleration
    c_bounce=1;     %Bouncing's coefficient of elasticity
    %Declaring ball's initial condition
    initpos=50;     %Ball's initial vertical position
    initvel=0;      %Ball's initial vertical velocity
    %Declaring time step
    dt=0.0125;      %Animation timestep
end
%Declaring class properties
properties
    %Declaring variables for figure, axes, and plot objects
    fig;        %Class' figure handle
    axs;        %Class' axes handle
    ball;       %Class' rectangle object for ball
    ground;     %Class' line object for ground
    %Declaring variable for animation
    anim;       %Class' timer object
    pos;        %Ball's current vertical position
    vel;        %Ball's current vertical velocity
end
%Declaring class method
methods
    %Declaring constructor
    function this=TBouncingBallClass_B()
        %Initiating GUI figure, axes, and objects for animation
        this.fig=figure('WindowStyle','Docked',...
                        'DeleteFcn',@(src,event)closefigurefcn(this));
        this.axs=axes('Parent',this.fig);
        this.ball=rectangle('Position',[-TBouncingBallClass_A.r_ball,...
                                        TBouncingBallClass_A.initpos,...
                                        TBouncingBallClass_A.r_ball,...
                                        TBouncingBallClass_A.r_ball],...
                            'Curvature',[1,1],...
                            'FaceColor','b',...
                            'Parent',this.axs);
        this.ground=line([-5*TBouncingBallClass_A.r_ball,...
                          5*TBouncingBallClass_A.r_ball],...
                         [0,0],...
                         'Parent',this.axs);
        axis(this.axs,[-5*TBouncingBallClass_A.r_ball,...
                       5*TBouncingBallClass_A.r_ball,...
                       0,...
                       TBouncingBallClass_A.initpos+...
                       2*TBouncingBallClass_A.r_ball]);
        axis(this.axs,'equal');
        axis(this.axs,'off');
        %Creating timer object
        this.anim=timer('TimerFcn',@(src,event)...
                                     runanimationfcn(this,src,event),...
                        'ExecutionMode','fixedRate',...
                        'Period',TBouncingBallClass_A.dt,...
                        'TasksToExecute',Inf);
        %Initiating ball's position and velocity
        this.pos=TBouncingBallClass_A.initpos-TBouncingBallClass_A.r_ball;
        this.vel=TBouncingBallClass_A.initvel;
    end
    %Declaring destructor
    function delete(this)
        delete(this.anim);
        clear all
        clear classes
    end
    %Declaring function to reset the ball
    function resetBall(this)
        this.pos=TBouncingBallClass_A.initpos-TBouncingBallClass_A.r_ball;
        this.vel=TBouncingBallClass_A.initvel;
    end
    %Declaring function to change ball's height
    function putBallAt(this,h)
        if (h<0)&&(h>TBouncingBallClass_A.initpos)
            disp('Cannot put the ball above 50m!');
            return;
        end
        if h>50
            this.pos=50;
        else
            this.pos=h;
        end
        this.vel=0;
    end
    %Declaring function to start animation
    function play(this)
        start(this.anim);
    end
    %Declaring function to pause animation
    function stop(this)
        stop(this.anim);
    end
    %Declaring callback function to run the animation
    function runanimationfcn(this,src,event)
        %Updating ball's position and velocity
        this.pos = this.pos+(this.vel*TBouncingBallClass_A.dt);
        this.vel = this.vel-...
                   (TBouncingBallClass_A.gravity*TBouncingBallClass_A.dt);
        if this.pos<0
            this.vel = -this.vel*TBouncingBallClass_A.c_bounce;
        end
        %Updating ball
        set(this.ball,'Position',[-TBouncingBallClass_A.r_ball,...
                                  this.pos,...
                                  TBouncingBallClass_A.r_ball,...
                                  TBouncingBallClass_A.r_ball]);
        %Preserving axes
        axis(this.axs,[-5*TBouncingBallClass_A.r_ball,...
                       5*TBouncingBallClass_A.r_ball,...
                       0,...
                       TBouncingBallClass_A.initpos+...
                       2*TBouncingBallClass_A.r_ball]);
        axis(this.axs,'equal');
        axis(this.axs,'off');
    end
    %Declaring callback function to end animation
    function closefigurefcn(this)
        stop(this.anim);
        delete(this.anim);
        pause(1);
    end
end
%CodeEnd-------------------------------------------------------------------

end

The following video shows how TBouncingBallClass_B.m is applied to alter an animation while it is being played. Notice that the ball’s position in the animation is changed as putBallAt method is invoked. The animation is also started and paused whenever play and stop method is invoked. Keep in mind that depending on your own MATLAB desktop configuration, the arrangement and location of the animation figure may vary from what is shown in this video.

6. Summary

In short, to create animation with timer object, one should create a plot and a timer object whose TimerFcn callback function is set to update the plot, but without calling pause command. For constant pace animation, the timer object’s ExecutionMode property should be set to ‘fixedRate’ and TaskToExecute property to Inf, while Period property should be set to reflect the desired animation pace. Using timer object for animation allows command window to accept any command that can be used to alter the animation while it is being played, however, this concept can only be done if the animation is written as class m-file.

6. Resource (Example M-File)

Script02a.m – script m-file for timer object’s hello world

Script02b.m – script m-file for sinusoidal animation with timer object

TBouncingBallFunction.m – function m-file for bouncing ball animation with timer object

TBouncingBallClass_A.m – class m-file for bouncing ball animation with timer object

TBouncingBallClass_B.m – class m-file for bouncing ball animation with timer object

FAQ

<to be added>

***

This tutorial is not perfect! If you still have any question or suggestion or correction regarding this tutorial, please feel free to leave a comment or email me at zerocross_raptor@yahoo.com.

***

Leave a comment