© Irfan Turk 2019
I. TurkPractical MATLABhttps://doi.org/10.1007/978-1-4842-5281-9_7

7. Data Visualization and Animation

Irfan Turk1 
(1)
Nilufer, Bursa, Turkey
 

MATLAB provides very powerful techniques to visualize data. In this chapter, we look at how to visualize data and create animations. Visualizing data was already touched on in Chapter 1. Therefore, the animation techniques are emphasized in this chapter. Animations can be created by using three basic techniques in MATLAB. These methods can be summarized as updating coordinates, applying transformation to objects, and creating movies.

Data Visualization

We already learned how to visualize two-dimensional data Chapter 1 for both single plots and multiple plots in a figure. In this section we learn how to visualize three-dimensional data (Table 7-1).
Table 7-1

Some Functions Related to 3-D Plotting

Function

Description

plot3(x,y,z)

Creates a 3-D line plot

bar3

Plots 3-D bar graphs

comet3(x,y,z)

Plots an animated 3-D graph

ezmesh

Visualizes the function in 3-D

ezplot3

A 3-D parametric curve plotter

mesh(x,y,z)

Creates a meshed-surface plot

pie3

Draws a 3-D pie chart

scatter3

Is a 3-D scatter plot function

stem3

Creates a 3-D stem plot

surf

Plots a 3-D shaded surface

waterfall

Creates a waterfall plot

Example 7-1. Consider the three-dimensional function given here.

0 ≤ t ≤ 4π, x = sin (t), y = cos (t), z = t.

Plot the graph of x, y, and z in a single figure.

Solution 7-1. The following code can be used to accomplish the given task.

Example7p1.m
%Example7p1
%This code plots 3-D
close all;
t = linspace(0,8*pi,1000);
x=sin(3*t);y=cos(2*t)-5;z=3*t;
plot3(x,y,z)
xlabel('sin(t)');
ylabel('cos(t)');
zlabel('t');
grid on
title('3-D Plot')
In this code, the close all command closes all the active figures drawn when it is called. Once the code is run, the output shown in Figure 7-1 is displayed.
../images/483991_1_En_7_Chapter/483991_1_En_7_Fig1_HTML.jpg
Figure 7-1

Output of Example7p1

There are two important functions that produce values with two variables in MATLAB, namely, peaks and meshgrid.

The function peaks(x,y) produces a 49 × 49 matrix by default via Gaussian distribution. The function meshgrid(x,y) replicates the grid vectors x and y to produce a full grid.

Using the functions [X,Y,Z] = peaks(x,y,z) and [X,Y,Z] = meshgrid(x,y,z), it is possible to create three variables, as well.

Example 7-2. Write code that plots two different functions onto two separate figures. The first plot belongs to the following function (which plots the Mexican hat):
$$ frac{sin left(sqrt{x^2+{y}^2}
ight)}{sqrt{x^2+{y}^2}} $$
where x and y are between -8 and 8. The second function (which plots a cowboy hat) is
$$ frac{sin left(3{x}^2+2{y}^2
ight)}{x^2+{y}^2} $$

where x and y are between -1.5 and 1.5.

Solution 7-2. The following code can be used to accomplish the given task.

Example7p2.m
%Example7p2
%This code uses meshgrid and surf
close all;
[x,y] = meshgrid(linspace(-8,8,30));
[xx,yy]=meshgrid(linspace(-1.5,1.5,30),...
    linspace(-1.5,1.5,30));
z1 = sin (sqrt(x.^2+y.^2))./sqrt(x.^2+y.^2);
z2 = sin(3*xx.^2+2*yy.^2)./(xx.^2+yy.^2);
figure(1)
surf(z1), shading flat
title('Mexican Hat');
figure(2)
surf(z2), shading faceted
title('Cowboy Hat');
% other possible shadings: flat, faceted, interp
Once the code is run, the resulting output is shown in Figures 7-2 and 7-3.
../images/483991_1_En_7_Chapter/483991_1_En_7_Fig2_HTML.jpg
Figure 7-2

First output of Example7p2

../images/483991_1_En_7_Chapter/483991_1_En_7_Fig3_HTML.jpg
Figure 7-3

Second output of Example7p2

Animation

Three techniques can be applied to create an animation with data: updating coordinates, applying transformation, and creating movies.

Updating Coordinates

In this type of animation, the object properties are updated and called within a loop. Most of the time these properties are the data of x and y coordinates as illustrated in Example 7-3.

Example 7-3. Consider the following function.
$$ y=sin left({x}^2
ight),0le xle 3pi $$

Write code to animate the function y by changing its coefficient.

Solution 7-3. The following code can be used to accomplish the given task.

Example7p3.m
%Example7p3
%This code animates 2-D
x = 0:0.05:3*pi;
y = sin(x.^2);
N = length(x);
for i=1:N
    y_plot = (i/N)*y;
    plot(x,y_plot)
    axis([0,3*pi,-1,1]);
    xlabel('x values')
    ylabel('y values')
    title('Animating 2-D')
    pause(0.02)
end
grid on

In the preceding code, the function y is plotted with coefficients starting from $$ frac{1}{189} $$ to 1. After each plotting in the loop, the pause(0.02) command pauses the computer for 0.02 seconds to see the changes in each frame visually.

Once the code is run, the plot is animated. The plot shown in Figure 7-4 is the final frame of the animation.
../images/483991_1_En_7_Chapter/483991_1_En_7_Fig4_HTML.jpg
Figure 7-4

A snapshot of the output of Example7p3

Example 7-4. Write code that uses the drawnow function to show the animation. The code should draw lines in a circle.

Solution 7-4. The following code can be used to accomplish the given task.

Example7p4.m
%Example7p4
%This code animates 2-D
N=100;
Angle = linspace(-pi,pi,N);
xc = sin(Angle);yc = cos(Angle);
plot(xc,yc);axis equal
xt = [1 1 1 1];yt = [0 0 0 0];
hold on
t = area(xt,yt); % initialize flat triangle
for j = 1:N
    xt(j) = xc(j); % determine new vertex value
    yt(j) = yc(j);
    t.XData = xt; % update data
    t.YData = yt; % update data
    drawnow % display updates
end
title('Final Frame of Animation')
In the preceding code, the area function is used to plot yt values versus xt values and fills the area between 0 and yt. Inside the for loop, the plotted data are updated and displayed with the drawnow function. Once the code is run, the output shown in Figure 7-5 is obtained, which is the final frame of the animation of the code.
../images/483991_1_En_7_Chapter/483991_1_En_7_Fig5_HTML.jpg
Figure 7-5

A snapshot of the output of Example7p4

Applying Transformation

In this technique, transformation is applied to objects. The function hgtransform is used to create the transform object.

Example 7-5. Write code to animate a 3-D star around the z-axis while the star is scaled from a large size to a smaller size by using the hgtransform .

Solution 7-5. The following code can be used to accomplish the given task.

Example7p5.m
%Example7p5
%This code uses hgtransform function
ax = axes('XLim',[-1.5,1.5],...
    'YLim',[-1.5,1.5],'ZLim',[-1.5,1.5]);
view(3) %sets for 3-d view
grid on
[x,y,z] = cylinder([.1 0]);
h(1) = surface(x,y,z,'FaceColor','yellow');
h(2) = surface(x,y,-z,'FaceColor','cyan');
h(3) = surface(z,x,y,'FaceColor','magenta');
h(4) = surface(-z,x,y,'FaceColor','green');
h(5) = surface(y,z,x,'FaceColor','blue');
h(6) = surface(y,-z,x,'FaceColor','red');
t = hgtransform('Parent',ax);
set(h,'Parent',t)
Rz = eye(4);Sxy = Rz;
for r = 1:.1:2*pi
    Rz = makehgtform('zrotate',r);
    % Scaling matrix
    Sxy = makehgtform('scale',r/5);
    set(t,'Matrix',Rz/Sxy)
    drawnow
    pause(0.02)
    if r == 3.6
        f = getframe;
    end
end
imshow(f.cdata)
title('Frame at r=3.6')
Once the code is run, the output shown in Figure 7-6 is obtained.
../images/483991_1_En_7_Chapter/483991_1_En_7_Fig6_HTML.jpg
Figure 7-6

Output of Example7p5

Creating Movies

Creating a movie is another method to animate the data. In this method, the picture of each drawing in each iteration is obtained using the getframe function . Then, using the movie function , the animation is created.

Example 7-6. For the following function given by
$$ y=sin (t),0le tle 2pi, $$

write code to animate the function y as a movie.

Solution 7-6. The following code can be used to accomplish the given task.

Example7p6.m
%Example7p6
%This code creates a movie
t=linspace(0,2*pi,1000);Count=1;
figure('Name',...%'NumberTitle','off')
    'Original Draw','Menu','none')
for freq=0:0.1:2*pi
          y=sin(freq*t);
          plot(t,y);
          xlabel('2 pi');ylabel('Results');
          axis([0,2*pi,-1,1])
          Script1=sprintf('y(t)=sin(%.1f t)',freq);
          title('Sinusoidal Function');
          text(1,0.5,Script1)
          M(Count)=getframe;Count=Count+1;
end
figure('Name',...
    'Playing Created Animation twice','Menu','none')
movie(M,2);
Once the code is run, the output is shown in Figure 7-7.
../images/483991_1_En_7_Chapter/483991_1_En_7_Fig7_HTML.jpg
Figure 7-7

The second output of the program Example7p6

When you want to save the movie that you created, use the functions writeVideo and VideoWriter.

Example 7-7. Create a movie by using the functions peaks and surf. Then, save the movie as an *.avi file.

Solution 7-7. The following code can be used to create the *.avi file .

Example7p7.m
%Example7p7
%This code saves the movie as *.avi
myVideo = VideoWriter('myfile.avi');
uncompressedVideo = VideoWriter('myfile.avi',...
    'Uncompressed AVI');
myVideo.FrameRate = 40;
myVideo.Quality = 100;
open(myVideo); % Open file to write
L = peaks;
surf(L);
axis tight manual
set(gca,'nextplot','replacechildren');
for m = 1:60
   surf(sin(2*pi*m/20)*L,L)
   frame = getframe;
   writeVideo(myVideo, frame);
end
close(myVideo);%close file

In this code, the function VideoWriter creates a video writer object. The class of this object is the same as its name, VideoWriter. Using the function writeVideo, the frames are written into that file. Once the code is executed, a file named myfile.avi is created and saved into your current directory.

Problems

  • 7.1. Consider the three-dimensional function given here.

0 ≤ t ≤ 2π, x = sin (2t), y = cos (3t), z = 5t
  • Plot the graph of x, y, and z in a single figure.

  • 7.2. Consider the following function.

$$ y=sin left({x}^3
ight),0le xle pi $$
  • Write code to animate the function y by changing its coefficient.

  • 7.3. Write code that uses the drawnow function to show the animation. The code should draw lines in a square.

  • 7.4. Write a code to animate a 3-D star around the y-axis while the star is scaled from a small size to a larger size using the hgtransform function.

  • 7.5. For the following function given by

$$ y=sin (2t),0le tle pi, $$
  • write code to animate the function y twice as a movie and save the created animation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.225.113