© Michael Paluszek and Stephanie Thomas  2019
Michael Paluszek and Stephanie ThomasMATLAB Machine Learning Recipeshttps://doi.org/10.1007/978-1-4842-3916-2_3

3. MATLAB Graphics

Michael Paluszek1  and Stephanie Thomas1
(1)
Plainsboro, NJ, USA
 

One of the issues with machine learning is understanding the algorithms and why an algorithm made a particular decision. In addition, you want to be able to easily understand the decision. MATLAB has extensive graphics facilities that can be harnessed for that purpose. Plotting is used extensively in machine learning problems. MATLAB plots can be two- or three-dimensional. MATLAB also has many plot types such as line plots, bar charts, and pie charts. Different types of plots are better at conveying particular types of data. MATLAB also has extensive surface and contour plotting capabilities that can be used to display complex data in an easy-to-grasp fashion. Another facility is 3D modeling. You can draw animated objects, such as robots or automobiles. These are particularly valuable when your machine learning involves simulations.

An important part of MATLAB graphics is Graphical User Interface (GUI) building. MATLAB has extensive facilities for making GUIs. These can be a valuable way of making your design tools or machine learning systems easy for users to operate.

This chapter will provide an introduction to a wide variety of graphics tools in MATLAB. They should allow you to harness MATLAB graphics for your own applications.

3.1 2D Line Plots

3.1.1 Problem

You want a single function to generate two-dimensional line graphs, avoiding a long list of code for the generation of each graphic.

3.1.2 Solution

Write a single function to take the data and parameter pairs to encapsulate the functionality of MATLAB’s 2D line plotting functions. An example of a plot created with a single line of code is shown in Figure 3.1.
../images/420697_2_En_3_Chapter/420697_2_En_3_Fig1_HTML.png
Figure 3.1

PlotSet’s built-in demo.

3.1.3 How It Works

PlotSet generates 2D plots, including multiple plots on a page.

function h = PlotSet( x, y, varargin )

This code processes varargin as parameter pairs to set options. A parameter pair is two inputs. The first is the name of the value and the second is the value. For example, the parameter pair for labeling the x-axis is:

’x label’,’Time ( s) ’

varargin makes it easy to expand the plotting options. The core function code is shown below. We supply default values for the x and y axis labels and the figure name. The parameter pairs are handled in a switch statement. The following code is the branch when there is only one x-axis label for all of the plots. It arranges plots by the data in plotSet that is a cell array.

    for k = 1:m
      subplot(m,nCol,k);
     j = plotSet{k};
      for i = 1:length(j)
       plotXY(x,y(j(i),:),plotType);
        hold on
      end
      hold off
      xlabel(xLabel{1});
      ylabel(yLabel{k});
      iflength(plotTitle) == 1 )
        title(plotTitle{1})
      else
        title(plotTitle{k})
      end
      if( ~isempty(leg{k}) )
        legend(leg{k});
      end
      grid on
    end

The plotting is done in a subfunction called plotXY. There you see all the familiar MATLAB plotting function calls.

 switch  type
   case  ’plot’
      plot(x,y);
   case { ’log’  ’loglog’  ’log␣log’}
      loglog(x,y);
   case { ’xlog’  ’semilogx’  ’x␣log’}
      semilogx(x,y);
   case { ’ylog’  ’semilogy’  ’y␣log’}
      semilogy(x,y);
   otherwise
      error( ’%s␣is␣not␣an␣available␣plot␣type’,type);
end
The example in Figure 3.1 is generated by a dedicated demo function at the end of the PlotSet function. This demo shows several of the features of the function. These include:
  1. 1.

    Multiple lines per graph

     
  2. 2.

    Legends

     
  3. 3.

    Plot titles

     
  4. 4.

    Default axes labels

     
Using a dedicated demo subfunction is a clean way of providing a built-in example of a function, and it is especially important in graphics functions to provide an example of a typical plot. The code is shown below.
function Demo
 x =  linspace (1,1000);
 y = [ sin (0.01*x); cos (0.01*x); cos (0.03*x)];
disp( ’PlotSet:␣One␣x␣and␣two␣y␣rows’)  

3.2 General 2D Graphics

3.2.1 Problem

You want to represent a 2D data set in different ways. Line plots are very useful, but sometimes it is easier to visualize data in different forms. MATLAB has many functions for 2D graphical displays.

3.2.2 Solution

Write a script to show MATLAB’s different 2D plot types. In our example we use subplots within one figure to help reduce figure proliferation.

3.2.3 How It Works

Use the NewFigure function to create a new figure window with a suitable name. Then run the following script.

 >> NewFigure( ’My␣figure␣name’)
ans =
   Figure (1: My  figure  name) with properties:
       Number: 1
         Name:  ’My␣figure␣name’
        Color: [0.9400 0.9400 0.9400]
     Position: [560 528 560 420]
        Units:  ’pixels’
   Show  all  properties
subplot(4,1,1);
plot(x,y);
subplot(4,1,2);
bar(x,y);
subplot(4,1,3);
 barh(x,y);
 ax4 =  subplot (4,1,4);
 pie(y)
colormap(ax4, ’gray’)  

Four plot types are shown that are helpful in displaying 2D data. One is the 2D line plot, the same as that used in PlotSet. The middle two are bar charts. The final is a pie chart. Each gives you different insight into the data. Figure 3.2 shows the plot types.

There are many MATLAB functions for making these plots more informative. You can:
  • Add labels

  • Add grids

../images/420697_2_En_3_Chapter/420697_2_En_3_Fig2_HTML.png
Figure 3.2

Four different types of MATLAB 2D plots.

  • Change font types and sizes

  • Change the thickness of lines

  • Add legends

  • Change axes limits

The last item requires looking at the axes’ properties. Here are the properties for the last plot – the list is very long! gca is the handle to the current axes. get( gca) returns a huge list, which we will not print here. Every single one of these can be changed by using the set function:

set(gca, ’YMinorGrid’, ’on’, ’YGrid’, ’on’)  

This uses parameter pairs just like PlotSet. In this list, children are pointers to the children of the axes. You can access those using get and change their properties using set. Any item that is added to an axis, such as axis labels, titles, lines, or other graphics objects, are all children of that axis.

3.3 Custom Two-Dimensional Diagrams

3.3.1 Problem

Many machine learning algorithms benefit from two-dimensional diagrams such as tree diagrams, to help the user understand the results and the operation of the software. Such diagrams, automatically generated by the software, are useful in many types of learning systems. This section gives an example of how to write MATLAB code for a tree diagram.

3.3.2 Solution

Our solution is to use the MATLAB patch function to automatically generate the blocks, and use line to generate connecting lines in the function TreeDiagram. Figure 3.3 shows the resulting hierarchical tree diagram. The circles are in rows and each row is labeled.

3.3.3 How It Works

Tree diagrams are very useful for machine learning. This function generates a hierarchical tree diagram with the nodes as circles with text within each node. The graphics functions used in this function are:

  1. 1.

    line

     
  2. 2.

    patch

     
  3. 3.

    text

     
The data needed to draw the tree are contained in a data structure, which is documented in the header. Each node has a parent field. This information is sufficient to make the connections. The node data are entered as a cell array.
../images/420697_2_En_3_Chapter/420697_2_En_3_Fig3_HTML.png
Figure 3.3

A custom tree diagram.

The function uses a figure handle as a persistent variable so that the same figure can be updated with subsequent calls, if desired.

if( ~update )
   figHandle = NewFigure(w.name);
else
    clf(figHandle)
end

The core drawing code is in DrawNode, which draws the boxes and ConnectNode, which connects the nodes with lines. Our nodes are circles with 20 segments. The linspace code makes sure that both 0 and 2π are not in the list of angles.

function [xC,yCT,yCB] = DrawNode( x0, y0, k, w )
 n = 20;
 a =  linspace (0,2* pi *(1-1/n),n);
 x = w.width* cos (a)/2 + x0;
 y = w.width* sin (a)/2 + y0;
patch(x,y, ’w’);
text(x0,y0,sprintf( ’%d’,k), ’fontname’,w.fontName, ’fontsize’,w.fontSize, ’horizontalalignment’, ’center’);
 xC  = x0;
 yCT = y0 + w.width/2;
 yCB = y0 - w.width/2;
  %% TreeDiagram>ConnectNode
function ConnectNode( n, nP, w )
 x = [n.xC nP.xC];
 y = [n.yCT nP.yCB];
line(x,y, ’linewidth’,w.linewidth, ’color’,w.linecolor);

The builtin in demo in TreeDiagram.

3.4 Three-Dimensional Box

There are two broad classes of three-dimensional graphics. One is to draw an object, like the earth. The other is to draw large data sets. This recipe plus the following one will show you how to do both.

3.4.1 Problem

We want to draw a three-dimensional box.

3.4.2 Solution

The function Box3 users the patch function to draw the object. An example is shown in Figure 3.4.

3.4.3 How It Works

Three-dimensional objects are created from vertices and faces. A vertex is a point in space. You create a list of vertices that are the corners of your 3D object. You then create faces that are lists of vertices. A face with two vertices is a line, one with three vertices is a triangle. A polygon can have as many vertices as you would like. However, at the lowest level, graphics processors deal with triangles so you are better off making all patches triangles.

You will notice the normal vector. This is the outward vector. Your vertices in your patches should be ordered using the right-hand rule, that is, if the normal is in the direction of your thumb, then the faces are ordered in the direction of your fingers. In this figure, the order for the two triangles would be:
../images/420697_2_En_3_Chapter/420697_2_En_3_Fig4_HTML.png
Figure 3.4

A box drawn with patch.

../images/420697_2_En_3_Chapter/420697_2_En_3_Fig5_HTML.png
Figure 3.5

A patch. The normal is toward the camera or the “outside” of the object.

 [3 2 1]
 [1 4 3]  

MATLAB lighting is not very picky about vertex ordering, but if you export a model, then you will need to follow this convention. Otherwise, you can end up with inside-out objects!

The following code creates a box composed of triangle patches. The face and vertex arrays are created by hand. Vertices are one vertex per row so vertex arrays are n by 3. Face arrays are n by m where m is the largest number of vertices per face. In Box we work with triangles only. All graphics processors ultimately draw triangles so, if you can, it is best to create objects only with triangles.

function [v, f] = Box( x, y, z )
  % Demo
ifnargin < 1 )
   Demo
    return
end
  % Faces
 f   = [2 3 6;3 7 6;3 4 8;3 8 7;4 5 8;4 1 5;2 6 5;2 5 1;1 3 2;1 4 3;5 6 7;5 7 8];
  % Vertices
 v = [-x  x  x -x -x  x  x -x;...
      -y -y  y  y -y -y  y  y;...
      -z -z -z -z  z  z  z  z]’/2;
  % Default outputs
ifnargout == 0 )
   DrawVertices( v, f,  ’Box’ );
    clear v
end

The box is drawn using patch in the function DrawVertices. There is just one call to patch. patch accepts parameter pairs to specify face and edge coloring and many other characteristics of the patch. Only one color can be specified for a patch. If you wanted a box with different colors on each side, you would need multiple patches. We turn on rotate3d so that we can reorient the object with the mouse. view3 is a standard MATLAB view with the eye looking down a corner of the grid box.

 NewFigure(name)
patch( ’vertices’,v, ’faces’,f, ’facecolor’,[0.8 0.1 0.2]);
axis image
xlabel( ’x’)
ylabel( ’y’)
zlabel( ’z’)
 See SimGUI.m and SimGUI.fig.
view(3)
grid on
 rotate3d on  

We use only the most basic lighting. You can add all sorts of lights in your drawing using light. Light can be ambient or from a variety of light sources.

3.5 Draw a 3D Object with a Texture

3.5.1 Problem

We want to draw a planet with a texture.

3.5.2 Solution

Use a surface and overlay a texture onto the surface. Figure 3.6 shows an example with a recent image of Pluto using the function Globe.

 >> Globe
ans =
   Figure (2: Globe) with properties:
       Number: 2
         Name:  ’Globe’
        Color: [0.9400 0.9400 0.9400]
     Position: [560 528 560 420]
        Units:  ’pixels’
   Show  all  properties
../images/420697_2_En_3_Chapter/420697_2_En_3_Fig6_HTML.jpg
Figure 3.6

A three-dimensional globe of Pluto.

3.5.3 How It Works

We generate the picture by first creating x, y, z points on the sphere and then overlaying a texture that is read in from an image file. The texture map can be read from a file using imread. If this is color, it will be a three-dimensional matrix. The third element will be an index to the color, red, blue or green. However, if it is a grayscale image, you must create the three-dimensional “color” matrix by replicating the image.

 p = imread( ’PlutoGray.png’);
 p3(:,:,1) = p;
 p3(:,:,2) = p;
 p3(:,:,3) = p;  

The starting p is a two-dimensional matrix.

You first generate the surface using the coordinates generated from the sphere function. This is done with surface. You then apply the texture:

   planetMap(:,:,i)= flipud (planetMap(:,:,i));
end
set(hSurf, ’Cdata’,planetMap, ’Facecolor’, ’texturemap’);
set(hSurf, ’edgecolor’,  ’none’,...
            ’EdgeLighting’,  ’phong’, ’FaceLighting’,  ’phong’,...
            ’specularStrength’,0.1, ’diffuseStrength’,0.9,...
            ’SpecularExponent’,0.5, ’ambientStrength’,0.2,...
            ’BackFaceLighting’, ’unlit’);

flipup makes the map look “normal.” Phong is a type of lighting. It takes the colors at the vertices and interpolates the colors at the pixels on the polygon based on the interpolated normals. Diffuse and specular refer to different types of reflections of light. They aren’t too important when you apply a texture to the surface.

3.6 General 3D Graphics

3.6.1 Problem

We want to use 3D graphics to study a 2D data set. A 2D data set is a matrix or an n by m array.

3.6.2 Solution

Use MATLAB surface, mesh, bar and contour functions. TwoDDataDisplay gives an example of a random data set with different visualizations is shown in Figure 3.7.

3.6.3 How It Works

We generate a random 2D data set that is 8x8 using rand. We display it in several ways in a figure with subplots. In this case, we create two rows and three columns of subplots. Figure 3.7 shows six types of 2D plots. surf, mesh and surfl (3D shaded surface with lighting) are very similar. The surface plots are more interesting when lighting is applied. The two bar3 plots show different ways of coloring the bars. In the second bar plot, the color varies with length. This requires a bit of code changing the CData and FaceColor.

 m =  rand (8,8);
 h = NewFigure( ’Two␣Dimensional␣Data’);
colormap(h, ’gray’)
subplot(2,3,1)
surf(m)
title( ’surf’)
subplot(2,3,2)
surfl(m, ’light’)
title( ’surfl’)
subplot(2,3,3)
mesh(m)
title( ’mesh’)
subplot(2,3,4)
 bar3(m)
title( ’bar3’)
subplot(2,3,5)
 h = bar3(m);
title( ’bar3’)
colorbar
for k = 1:length(h)
         zdata = h(k).ZData;
         h(k).CData = zdata;
         h(k).FaceColor =  ’interp’;
end
subplot(2,3,6)
contour(m);
title( ’contour’)

3.7 Building a GUI

3.7.1 Problem

We want a GUI to provide a graphical interface for a second-order system simulation.

3.7.2 Solution

We will use the MATLAB GUIDE to build a GUI that will allow us to:
  1. 1.

    Set the damping constant

     
  2. 2.

    Set the end time for the simulation

     
  3. 3.

    Set the type of input (pulse, step or sinusoid)

     
  4. 4.

    Display the inputs and outputs plot

     

3.7.3 How It Works

We want to build a GUI to interface with SecondOrderSystemSim shown below. The first part of SecondOrderSystemSim is the simulation code in a loop.

 omega   =  max ([d.omega d.omegaU]);  % Maximum frequency for the simulation
 dT      = 0.1*2* pi /omega;  % Get the time step from the frequency
 n       =  floor (d.tEnd/dT);  % Get an integer numbeer of steps
 xP      =  zeros (2,n);  % Size the plotting array
 x       = [0;0];  % Initial condition on the [position;velocity]
 t       = 0;  % Initial time
for k = 1:n
   [~,u]   = RHS(t,x,d);
   xP(:,k) = [x(1);u];
   x       = RungeKutta( @RHS, t, x, dT, d );
   t       = t + dT;
end
../images/420697_2_En_3_Chapter/420697_2_En_3_Fig7_HTML.png
Figure 3.7

Two-dimensional data shown with six different plot types.

Running it gives the following plot Figure 3.8. The plot code is
../images/420697_2_En_3_Chapter/420697_2_En_3_Fig8_HTML.png
Figure 3.8

Second-order system simulation.

 [t,tL] = TimeLabel((0:n-1)*dT);
ifnargout == 0 )
   PlotSet(t,xP, ’x␣label’,tL, ’y␣label’, { ’x’  ’u’},  ’figure␣title’, ’Filter’);
end

TimeLabel makes time units that are reasonable for the length of the simulation. It automatically rescales the time vector. The function has the simulation loop built in.

The MATLAB GUI building system, GUIDE, is invoked by typing guide at the command line. We are using MATLAB R2018a. There may be subtle differences in your version.

There are several options for GUI templates, or a blank GUI. We will start from a blank GUI. First, let’s make a list of the controls we will need from our desired features list above:
  • Edit boxes for:
    • Simulation duration

    • Damping ratio

    • Undamped natural frequency

    • Sinusoid input frequency

    • Pulse start and stop time

    ../images/420697_2_En_3_Chapter/420697_2_En_3_Fig9_HTML.jpg
    Figure 3.9

    Blank GUI.

  • Radio button for the type of input

  • Run button for starting a simulation

  • Plot axes

We type “guide” in the command window and it asks us to either pick an existing GUI or create a new one. We choose a blank GUI. Figure 3.9 shows the template GUI in GUIDE before we make any changes to it. You add elements by dragging and dropping from the table at the left.

Figure 3.10 shows the GUI inspector. You edit GUI elements here. You can see that the elements have a lot of properties. We aren’t going to try and make this GUI really slick, but with some effort you can make it a work of art. The ones we will change are the tag and text properties. The tag gives the software a name to use internally. The text is just what is shown on the device.

We then add all the desired elements by dragging and dropping. We choose to name our GUI “GUI”. The resulting initial GUI is shown in Figure 3.11. In the inspector for each element you will see a field for “tag.” Change the names from things like edit1 to names you can easily identify. When you save them and run the GUI from the .fig file the code in GUI.m will automatically change.

We create a radio button group and add the radio buttons. This handles disabling all but the selected radio button. When you hit the green arrow in the layout box, it saves all changes to the m-file and also simulates it. It will warn you about bugs.
../images/420697_2_En_3_Chapter/420697_2_En_3_Fig10_HTML.jpg
Figure 3.10

The GUI inspector.

At this point, we can start work on the GUI code itself. The template GUI stores its data, calculated from the data the user types into the edit boxes, in a field called simdata. The autogenerated code is in SimGUI.

When the GUI loads, we initialize the text fields with the data from the default data structure. Make sure that the initialization corresponds to what is seen in the GUI. You need to be careful about radio buttons and button states.

function SimGUI_OpeningFcn(hObject, eventdata, handles, varargin)
  % Choose default command line output for SimGUI
 handles.output = hObject;
  % Get the default data
 handles.simData = SecondOrderSystemSim;
  % Set the default states
set(handles.editDuration, ’string’,num2str(handles.simData.tEnd));
set(handles.editUndamped, ’string’,num2str(handles.simData.omega));
set(handles.editPulseStart, ’string’,num2str(handles.simData.tPulseBegin));
set(handles.editPulseEnd, ’string’,num2str(handles.simData.tPulseEnd));
set(handles.editDamping, ’string’,num2str(handles.simData.zeta));
set(handles.editInputFrequency, ’string’,num2str(handles.simData.omegaU));
  % Update handles structure
 guidata(hObject, handles);  
../images/420697_2_En_3_Chapter/420697_2_En_3_Fig11_HTML.jpg
Figure 3.11

Snapshot of the GUI in the editing window after adding all the elements.

When the start button is pushed we run the simulation and plot the results. This essentially is the same as the demo code in the second-order simulation.

function start_Callback(hObject, eventdata, handles)
 [xP, t, tL] = SecondOrderSystemSim(handles.simData);
axes(handles.position)
plot(t,xP(1,:));
ylabel( ’Position’)
grid
axes(handles.input)
plot(t,xP(2,:));
xlabel(tL);
ylabel( ’input’);
grid
../images/420697_2_En_3_Chapter/420697_2_En_3_Fig12_HTML.jpg
Figure 3.12

Snapshot of the GUI in simulation.

The callbacks for the edit boxes require a little code to set the data in the stored data. All data are stored in the GUI handles. guidata must be called to store new data in the handles.

function editDuration_Callback(hObject, eventdata, handles)
 handles.simData.tEnd = str2double( get (hObject, ’String’));
 guidata(hObject, handles);  

One simulation is shown in Figure 3.12. Another simulation in the GUI is shown in Figure 3.13.

3.8 Animating a Bar Chart

Two-dimensional arrays are often produced as part of machine-learning algorithms. For situations where they change dynamically we would like to animate a display.
../images/420697_2_En_3_Chapter/420697_2_En_3_Fig13_HTML.jpg
Figure 3.13

Snapshot of the GUI in simulation.

3.8.1 Problem

We want to animate a 3D bar chart.

3.8.2 Solution

We will write code to animate the MATLAB bar3 function.

3.8.3 How It Works

Our function Bar3D will set up the figure using bar3 and then replace the values for the length of the bars. This is trickier than it sounds.

The following is an example of bar3. We use the handle to get the z data.

 >> m = [1 2 3;4 5 6];
 h = bar3(m);
 >> z =  get (h(1), ’zdata’)
 z =
    NaN     0     0   NaN
      0     1     1     0
      0     1     1     0
    NaN     0     0   NaN
    NaN     0     0   NaN
    NaN   NaN   NaN   NaN
    NaN     0     0   NaN
      0     4     4     0
      0     4     4     0
    NaN     0     0   NaN
    NaN     0     0   NaN
    NaN   NaN   NaN   NaN  

We see each column in the array. We will need to replace all four values for each number in m. Look at h. It is length 3. Each column in m has a surface data structure.

 >> h
 h =
   1x3 Surface array:
     Surface    Surface    Surface  

Figure 3.14 shows the bar graph.

The code is shown below. We have two actions, “initialize,” which creates the figure, and “update,” which updates the z values. Fortunately, the z-values are always in the same spot so it is not too hard to replace them. colorbar draws the color bar seen on the right of Figure 3.15. We use persistent to store the handle to bar3.
../images/420697_2_En_3_Chapter/420697_2_En_3_Fig14_HTML.png
Figure 3.14

Two by three bar chart.

ifnargin < 1 )
   Demo
    return
end
 persistent h
 switch  lower (action)
   case  ’initialize’
     NewFigure( ’3D␣Bar␣Animation’);
     h = bar3(v);
      colorbar
      xlabel(xL)
      xlabel(yL)
      xlabel(zL)
      title(t);
      view(3)
     rotate3d on
   case  ’update’
     nRows =  length (h);
      for i = 1:nRows
       z =  get (h(i), ’zdata’);
       n =  size (v,1);
       j = 2;
        for k = 1:n
         z(j,  2) = v(k,i);
         z(j,  3) = v(k,i);
         z(j+1,2) = v(k,i);
         z(j+1,3) = v(k,i);
         j        = j + 6;
        end
        set(h(i), ’zdata’,z);
      end
end
../images/420697_2_En_3_Chapter/420697_2_En_3_Fig15_HTML.png
Figure 3.15

Two by three bar chart and the end of the animation.

The figure at the end of the animation is shown in Figure 3.15.

3.9 Drawing a Robot

This section shows the elements of writing graphics code to draw a robot. If you are doing machine learning involving humans or robots, this is a useful code to have. We’ll show how to animate a robot arm.

3.9.1 Problem

We want to animate a robot arm.

3.9.2 Solution

We write code to create vertices and faces for use in the MATLAB patch function.

3.9.3 How It Works

DrawSCARA draws and animates a robot. The first part of the code really just organizes the operation of the function using a switch statement.

 switch(  lower (action) )
     case  ’defaults’
         m = Defaults;
     case  ’initialize’
          ifnargin < 2 )
             d   = Defaults;
          else
             d   = x;
          end
         p = Initialize( d );
     case  ’update’
          ifnargout == 1 )
             m = Update( p, x );
          else
             Update( p, x );
          end
end

Initialize creates the vertex and faces using functions Box, Frustrum and UChannel. These are tedious to write and are geometry-specific. You can apply them to a wide variety of problems, however. You should note that it stores the patches so that we just have to pass in new vertices when animating the arm. The “new” vertices are just the vertices of the arm rotated and translated to match the position of the arm. The arm itself does not deform. We do the computations in the right order so that transformations are passed up/down the chain to get everything moving correctly.

Update updates the arm positions by computing new vertices and passing them to the patches. drawnow draws the arm. We can also save the frames to animate it using MATLAB’s movie functions.

function m = Update( p, x )
for k = 1:size(x,2)
      % Link 1
     c       =  cos (x(1,k));
     s       =  sin (x(1,k));
     b1      = [c -s 0;s c 0;0 0 1];
     v       = (b1*p.v1’)’;
      set(p.link1, ’vertices’,v);
      % Link 2
     r2      = b1*[p.a1;0;0];
           c       =  cos (x(2,k));
     s       =  sin (x(2,k));
     b2      = [c -s 0;s c 0;0 0 1];
     v       = (b2*b1*p.v2’)’;
     v(:,1)  = v(:,1) + r2(1);
     v(:,2)  = v(:,2) + r2(2);
      set(p.link2, ’vertices’,v);
      % Link 3
     r3      = b2*b1*[p.r3;0;0] + r2;
     v       = p.v3;
     v(:,1)  = v(:,1) + r3(1);
     v(:,2)  = v(:,2) + r3(2);
     v(:,3)  = v(:,3) + x(3,k);
      set(p.link3, ’vertices’,v);
      % Link 4
           c       =  cos (x(4,k));
     s       =  sin (x(4,k));
     b4      = [c -s 0;s c 0;0 0 1];
     v       = (b4*b2*b1*p.v4’)’;
     r4      = b2*b1*[p.r4;0;0] + r2;
     v(:,1)  = v(:,1) + r4(1);
     v(:,2)  = v(:,2) + r4(2);
     v(:,3)  = v(:,3) + x(3,k);
      set(p.link4, ’vertices’,v);
      ifnargout > 0 )
         m(k) =  getframe ;
      else
        drawnow;
      end
end
The SCARA robot arm in the demo is shown at the end in Figure 3.16. The demo code could be replaced by a simulation of the arm dynamics. In this case, we pick angular rates and generate an array of angles. Note that this alternate demo function does not need to be a built-in demo function at all. This same block of code can be executed directly from the command line.
../images/420697_2_En_3_Chapter/420697_2_En_3_Fig16_HTML.jpg
Figure 3.16

Robot arm generated by DrawSCARA.

 DrawSCARA(  ’initialize’ );
 t       =  linspace (0,100);
 omega1  = 0.1;
 omega2  = 0.2;
 omega3  = 0.3;
 omega4  = 0.4;
 x       = [ sin (omega1*t); sin (omega2*t);0.01* sin (omega3*t); sin (omega4*t)];
 DrawSCARA(  ’update’, x );

3.10 Summary

This chapter has demonstrated graphics that can help you to understand the results of machine learning software. Two- and three-dimensional graphics were demonstrated. The chapter also showed how to build a Graphical User Interface to help you to automate functions. Table 3.1 lists the functions and scripts included in the companion code.
Table 3.1

Chapter Code Listing

File

Description

Bar3D

3D bar plots

Box

Draw a box.

DrawSCARA

Draw a robot arm.

DrawVertices

Draw a set of vertices and faces.

Frustrum

Draw a frustrum (a cone with the top chopped off)

Globe

Draw a texture-mapped globe.

PlotSet

2D line plots.

SecondOrderSystemSim

Simulates a second-order system.

SimGUI

Code for the simulation GUI.

SimGUI.fig

The figure.

SurfaceOfRevolution

Draw a surface of revolution

TreeDiagram

Draw a tree diagram.

TwoDDataDisplay

A script to display two-dimensional data in three-dimensional graphics.

UChannel

Draw a U shaped channel