Generating a basic animation of a 2D figure

42 views (last 30 days)
I need to create an animation that translates a plot of a square in a diagonal motion while also shrinking and lightening the color of the square. I've never used animations before and I was told to use a for loop to create the animation. However all I have completed in generating all of the squares and they are all displayed on the same figure at the same time.
figure(1)
Square = [0,0,2,2;0,2,2,0];
fill(Square(1,:),Square(2,:), [1 0 .7])
title('Square Animation')
axis equal
hold on
fill((Square(1,:)*.9)+2,(Square(2,:)*.9)+2.1,[1 .2 .7])
fill((Square(1,:)*.8)+3.9,(Square(2,:)*.8)+4.1,[1 .3 .7])
fill((Square(1,:)*.7)+5.5,(Square(2,:)*.7)+5.8,[1 .4 .7])
fill((Square(1,:)*.6)+6.9,(Square(2,:)*.6)+7.4,[1 .5 .7])
fill((Square(1,:)*.5)+8.1,(Square(2,:)*.5)+8.7,[1 .6 .7])
fill((Square(1,:)*.4)+9.1,(Square(2,:)*.4)+10,[1 .7 .7])
fill((Square(1,:)*.3)+10,(Square(2,:)*.3)+10.9,[1 .8 .7])
fill((Square(1,:)*.2)+10.6,(Square(2,:)*.2)+11.7,[1 .9 .9])
fill((Square(1,:)*.15)+11,(Square(2,:)*.15)+12.4,[1 .93 .9])
fill((Square(1,:)*.1)+11.4,(Square(2,:)*.1)+13,[1 .97 .9])

Accepted Answer

Amit
Amit on 21 Jan 2014
something like this:
figure(1)
Square = [0,0,2,2;0,2,2,0];
fill(Square(1,:),Square(2,:), [1 0 .7])
title('Square Animation')
axis equal
hold on
A = [0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.15 0.1];
B = [2.1 4.1 5.8 7.4 8.7 10 10.9 11.7 12.4 13];
D = [2 3.9 5.5 6.9 8.1 9.1 10 10.6 11 11.4];
C = [1 .2 .7;1 .3 .7;1 .4 .7;1 .5 .7; 1 .6 .7;1 .7 .7;1 .8 .7;1 .9 .9;1 .93 .9;1 .97 .9];
for i = 1:numel(A)
fill((Square(1,:)*A(i))+D(i),(Square(2,:)*A(i))+B(i),C(i,:));
pause(0.5);
end
  1 Comment
Amit
Amit on 21 Jan 2014
for loop plots them in sequence and pause allows 0.5 seconds pause before plotting the next one.

Sign in to comment.

More Answers (1)

Bruno Pop-Stefanov
Bruno Pop-Stefanov on 21 Jan 2014
Edited: Bruno Pop-Stefanov on 21 Jan 2014
Using hold on will keep all previously drawn objects in your figure. Use hold off instead if you want only one square that animates.
Also, plotting a new object at each iteration using fill (or any other plotting function) is not the most efficient method. A faster method consists in plotting your object only once and then updating it using the set function.
Take a look at animation.m that I have attached to see how I would do it.
I use getframe to record a movie and then use the function movie to play the animation 20 times.

Categories

Find more on Animation in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!