Advanced Programming in MATLAB - Aaron Ponti PDF
Advanced Programming in MATLAB - Aaron Ponti PDF
Aaron Ponti
September 3, 2010
Abstract
In the first session of this course, we introduced some of the basic
concepts of MATLAB programming. In this lecture, we want to explore
some more advanced topics. Since the material we can cover is necessarily
limited, references are given in every chapter for self study.
Contents
1 Visualization 3
1.1 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 A MATLAB graph . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Figure toolbars . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 Types of plots . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4.1 Two-dimensional plotting functions . . . . . . . . . . 6
1.4.2 Three-dimensional plotting functions . . . . . . . . . 8
1.5 Interactive plots with the plot tools . . . . . . . . . . . . . . 9
1.6 Basic plotting commands . . . . . . . . . . . . . . . . . . . 9
1.6.1 Creating Figure Windows . . . . . . . . . . . . . . . 9
1.6.2 Displaying Multiple Plots per Figure . . . . . . . . . 10
1.6.3 Specifying the Target Axes . . . . . . . . . . . . . . 11
1.7 Using High-Level Plotting Functions . . . . . . . . . . . . . 12
1.7.1 Functions for Plotting Line Graphs . . . . . . . . . 12
1.7.2 Programmatic plotting . . . . . . . . . . . . . . . . . 12
1.7.3 Creating line plots . . . . . . . . . . . . . . . . . . . 13
1.7.4 Specifying line style . . . . . . . . . . . . . . . . . . 15
1.7.5 Colors, line styles, and markers . . . . . . . . . . . . 16
1.7.6 Specifying the Color and Size of Lines . . . . . . . . 17
1.7.7 Adding Plots to an Existing Graph . . . . . . . . . 18
1.7.8 Line Plots of Matrix Data . . . . . . . . . . . . . . 18
1.7.9 Plotting with two y-axes . . . . . . . . . . . . . . . . 20
1.7.10 Combining linear and logarithmic axes . . . . . . . . 21
1.8 Setting axis parameters . . . . . . . . . . . . . . . . . . . . 22
1.8.1 Axis Scaling and Ticks . . . . . . . . . . . . . . . . 22
1.8.2 Axis Limits and Ticks . . . . . . . . . . . . . . . . . 23
1.8.3 Semiautomatic Limits . . . . . . . . . . . . . . . . . 23
1.8.4 Axis tick marks . . . . . . . . . . . . . . . . . . . . . 23
1.8.5 Example — Specifying Ticks and Tick Labels . . . 23
1
1.8.6 Setting aspect ratio . . . . . . . . . . . . . . . . . . 24
1.9 Printing and exporting . . . . . . . . . . . . . . . . . . . . . 26
1.9.1 Graphical user interfaces . . . . . . . . . . . . . . . . 26
1.9.2 Command line interface . . . . . . . . . . . . . . . . 31
3 Object-oriented programming 54
3.1 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.2 Introduction to OOP . . . . . . . . . . . . . . . . . . . . . . 54
3.3 Classes in MATLAB . . . . . . . . . . . . . . . . . . . . . . 55
3.4 User-defined classes . . . . . . . . . . . . . . . . . . . . . . . 55
3.5 MATLAB classes - key terms . . . . . . . . . . . . . . . . . 55
3.6 Handle vs. value classes . . . . . . . . . . . . . . . . . . . . 56
3.7 Class folders . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
3.8 Class building blocks . . . . . . . . . . . . . . . . . . . . . . 57
3.8.1 The classdef block . . . . . . . . . . . . . . . . . . . 57
3.8.2 The properties block . . . . . . . . . . . . . . . . . . 58
3.8.3 The methods block . . . . . . . . . . . . . . . . . . . 60
3.8.4 The events block . . . . . . . . . . . . . . . . . . . . 62
3.8.5 Specifying attributes . . . . . . . . . . . . . . . . . . 63
3.9 Example: a polynomial class . . . . . . . . . . . . . . . . . 64
3.9.1 Creating the needed folder and file . . . . . . . . . . 64
3.9.2 Using the DocPolynom Class . . . . . . . . . . . . . 64
3.9.3 The DocPolynom Constructor Method . . . . . . . . 65
3.9.4 Converting DocPolynom Objects to Other Types . . 66
3.9.5 The DocPolynom disp method . . . . . . . . . . . . 69
3.10 Defining the + Operator . . . . . . . . . . . . . . . . . . . . 69
3.11 Overloading MATLAB Functions roots and polyval for the
DocPolynom Class . . . . . . . . . . . . . . . . . . . . . . . 70
3.11.1 Defining the roots function . . . . . . . . . . . . . . 70
3.11.2 Defining the polyval function . . . . . . . . . . . . . 71
3.11.3 Complete DocPolynom example . . . . . . . . . . . . 71
2
4.4 Simplifying Java Class Names . . . . . . . . . . . . . . . . . 73
4.5 Creating and using Java objects . . . . . . . . . . . . . . . . 74
4.5.1 Constructing Java objects . . . . . . . . . . . . . . . 74
4.5.2 Invoking methods on Java objects . . . . . . . . . . 74
4.5.3 Obtaining information about methods . . . . . . . . 74
4.6 Passing arguments to and from a Java method . . . . . . . 76
4.6.1 Conversion of MATLAB data types . . . . . . . . . 76
4.6.2 Conversion of Java return data types . . . . . . . . . 77
1 Visualization
1.1 References
• http://www.mathworks.com/access/helpdesk/help/techdoc/creating_plots/bqrw9tj.html
• http://www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/graphg.pdf
h = figure;
By default, figure windows are resizable and include pull-down menus and tool-
bars.
A plot is any graphic display you can create within a figure window. Plots
can display tabular data, geometric objects, surface and image objects, and
annotations such as titles, legends, and colorbars. Figures can contain any
3
number of plots. Each plot is created within a 2-D or a 3-D data space called
an axes. You can explicitly create axes with the axes or subplot functions.
A graph is a plot of data within a 2-D or 3-D axes. Most plots made with
MATLAB functions and GUIs are therefore graphs. When you graph a one-
dimensional variable (e.g., rand(100,1)), the indices of the data vector (in this
case 1:100 ) become assigned as x values, and plots the data vector as y values.
Some types of graphs can display more than one variable at a time, others
cannot.
x = 0:.2:20;
y = sin(x)./sqrt(x+1);
y(2,:) = sin(x/2)./sqrt(x+1);
y(3,:) = sin(x/3)./sqrt(x+1);
plot(x,y)
4
This graphic identifies the components and tools of a figure window.
You can enable two other toolbars from the View menu:
• Camera toolbar. Use for manipulating 3-D views, with camera, light,
and projection controls.
5
• Plot Edit toolbar. Use for annotation and setting plot and object prop-
erties.
help plotyy
6
7
1.4.2 Three-dimensional plotting functions
The table below shows all available MATLAB 3-D and volumetric plot functions.
It includes functions that generate 3-D data (cylinder, ellipsoid, sphere), but
most plot either arrays of data or functions.
8
1.5 Interactive plots with the plot tools
Most of the plotting functions shown in the previous tables are accessible through
the Figure Palette, one of the Plot Tools you can access via the figure win-
dow View menu. When the Figure Palette is active and you select one, two or
more variables listed within it, you can generate a plot of any appropriate type
by right-clicking and selecting a plot type from the context menu that appears.
The lowest item on that menu is More Plots. When you select More Plots,
the Plot Catalog opens for you to browse through all plot types and generate
one of them, either to display the variables you selected in the Figure Palette
or a MATLAB expression you can specify in the Plot Catalog window.
9
the last figure used or the last figure you clicked the mouse in). The figure
function creates figure windows. For example,
figure
creates a new window and makes it the current figure. You can make an existing
figure current by clicking it with the mouse or by passing its handle (the number
indicated in the window title bar), as an argument to figure.
figure(2)
h = figure
h =
3
t = 0:pi/20:2*pi;
[x,y] = meshgrid(t);
subplot(2,2,1); plot(sin(t),cos(t)); axis equal;
subplot(2,2,2); z = sin(x)+cos(y); plot(t,z); axis([0 2*pi -2 2]);
subplot(2,2,3); z = sin(x).*cos(y); plot(t,z); axis([0 2*pi -1 1]);
subplot(2,2,4); z = (sin(x).^2)-(cos(y).^2); plot(t,z); axis([0 2*pi -1 1]);
10
Each subregion contains its own axes with characteristics you can control
independently of the other subregions. This example uses the axis function to
set limits and change the shape of the subplots. See the axes, axis, and subplot
functions for more information.
h = get(gcf,’Children’);
11
subplot(h(1)); title(’Most recently created axes’);
subplot(gca); title(’Current active axes’);
The call
get(gcf,’Children’);
returns the handles of all the axes, with the most recently created one first. The
function gca returns the handle of the current active axes.
12
Step Typical code
1 Prepare your data x = 0:0.2:12;
y1 = bessel(1,x);
y2 = bessel(2,x);
y3 = bessel(3,x);
2 Select a window and position figure(1);
a plot region within the window subplot(2,2,1);
3 Call elementary plotting h = plot(x,y1,x,y2,x,y3);
function
4 Select line and marker set(h,’LineWidth’,2, ...
characteristics {’LineStyle’},{’–’;’:’;’-.’});
set(h,{’Marker’},{’none’;’o’;’x’ });
set(h,{’Color’},{’r’;’g’;’b’});
5 Set axis limits, tick marks, axis([0 12 -0.5 1]);
and grid lines grid on;
6 Annotate the graph with axis xlabel(’Time’);
labels, legend, and text ylabel(’Amplitude’);
legend(h,’First’,’Second’,’Third’);
title(’Bessel Functions’);
[y,ix] = min(y1);
text(x(ix),y,’First Min \rightarrow’, ...
’HorizontalAlignment’,’right’);
7 Export graph print -depsc -tiff -r200 myplot
t = 0:pi/100:2*pi;
y = sin(t);
plot(t,y);
grid on % Turn on grid lines for this plot
13
Appropriate axis ranges and tick mark locations are automatically selected.
You can plot multiple graphs in one call to plot using x-y pairs. MATLAB
automatically cycles through a predefined list of colors (determined by the axes
ColorOrder property) to allow discrimination between sets of data. Plotting
three curves as a function of t produces
y = sin(t);
y2 = sin(t-0.25);
y3 = sin(t-0.5);
plot(t,y,t,y2,t,y3)
14
1.7.4 Specifying line style
You can assign different line styles to each data set by passing line style identifier
strings to plot. For example,
plot(t,y,’-’,t,y2,’--’,t,y3,’:’)
15
The graph shows three lines of different colors and lines styles representing
the value of the sine function with a small phase shift between each line, as
defined by y, y2, and y3. The lines are blue solid, green dashed, and red dotted.
plot(x,y,’linestyle_marker_color’)
16
For example,
plot(x,y,’:squarey’)
plots a yellow dotted line and places square markers at each data point. If
you specify a marker type, but not a line style, only the marker is plotted.
The specification can consist of one or none of each specifier in any order. For
example, the string
’go--’
defines a dashed line with circular markers, both colored green. You can also
specify the size of the marker and, for markers that are closed shapes, you can
specify separately the colors of the edges and the face.
x = -pi:pi/10:pi;
y = tan(sin(x)) - sin(tan(x));
plot(x,y,’--rs’,’LineWidth’,2,...
’MarkerEdgeColor’,’k’,...
’MarkerFaceColor’,’g’,...
’MarkerSize’,10)
17
1.7.7 Adding Plots to an Existing Graph
You can add plots to an existing graph using the hold command. When you
set hold to on, MATLAB does not remove the existing graph; it adds the new
data to the current graph, rescaling if the new data falls outside the range of
the previous axis limits.
For example, these statements first create a semilogarithmic plot, then add
a linear plot.
semilogx(1:100,’+’)
hold all % hold plot and cycle line colors
plot(1:3:300,1:100,’--’)
hold off
grid on % Turn on grid lines for this plot
The x-axis limits are reset to accommodate the new data, but the scaling from
logarithmic to linear does not change.
18
plot(Y)
one line is plotted for each column of the matrix. The x-axis is labeled with the
row index vector 1:m, where m is the number of rows in Y. For example,
Z = peaks;
plot(Z)
In general, if plot is used with two arguments and if either X or Y has more
than one row or column, then:
• If Y is a matrix, and x is a vector, plot(x,Y) successively plots the rows or
columns of Y versus vector x, using different colors or line types for each.
The row or column orientation varies depending on whether the number of
elements in x matches the number of rows in Y or the number of columns.
If Y is square, its columns are used.
19
• If X is a matrix and y is a vector, plot(X,y) plots each row or column of X
versus vector y. For example, plotting the peaks matrix versus the vector
1:length(peaks) rotates the previous plot.
• If X and Y are both matrices of the same size, plot(X,Y) plots the columns
of X versus the columns of Y. You can also use the plot function with
multiple pairs of matrix arguments.
plot(X1,Y1,X2,Y2,...)
This statement graphs each X-Y pair, generating multiple lines. The dif-
ferent pairs can be of different dimensions.
t = 0:pi/20:2*pi;
y = exp(sin(t));
plotyy(t,y,t,y,’plot’,’stem’)
20
1.7.10 Combining linear and logarithmic axes
You can use plotyy to apply linear and logarithmic scaling to compare two data
sets having different ranges of values.
t = 0:900; A = 1000; a = 0.005; b = 0.005;
z1 = A*exp(-a*t);
z2 = sin(b*t);
[haxes,hline1,hline2] = plotyy(t,z1,t,z2,’semilogy’,’plot’);
This example saves the handles of the lines and axes created to adjust and label
the graph. First, label the axes whose y value ranges from 10 to 1000. This is
the first handle in haxes because it was specified first in the call to plotyy. Use
the axes function to make haxes(1) the current axes, which is then the target
for the ylabel function.
axes(haxes(1))
ylabel(’Semilog Plot’)
Now make the second axes current and call ylabel again.
21
axes(haxes(2))
ylabel(’Linear Plot’)
You can modify the characteristics of the plotted lines in a similar way. For
example, to change the line style of the second line plotted to a dashed line, use
the statement
set(hline2,’LineStyle’,’--’)
22
• axes — Creates a new axes object with the specified characteristics.
• get and set — Enable you to query and set a wide variety of properties of
existing axes.
• gca — Returns the handle (identifier) of the current axes. If there are
multiple axes in the figure window, the current axes is the last graph
created or the last graph you clicked on with the mouse. The following
two sections provide more information and examples
axis([xmin,xmax,ymin,ymax]);
axis([-Inf 5 2 2.5]);
x = -pi:.1:pi;
y = sin(x);
plot(x,y);
set(gca,’XTick’,-pi:pi/2:pi);
set(gca,’XTickLabel’,{’-pi’,’-pi/2’,’0’,’pi/2’,’pi’})
23
These functions (xlabel, ylabel, title, text) add axis labels and draw an arrow
that points to the location on the graph where y = sin(−π/4).
t = 0:pi/20:2*pi;
plot(sin(t),2*cos(t));
grid on
24
produces a graph with the default aspect ratio. The command
axis square
axis equal
This produces an axes that is rectangular in shape, but has equal scaling along
each axis. If you want the axes shape to conform to the plotted data, use the
tight option in conjunction with equal.
25
1.9 Printing and exporting
There are four basic operations that you can perform in printing or transferring
figures you’ve created with MATLAB graphics to specific file formats for other
applications to use.
Opeation Description
Print Send a figure from the screen directly
to the printer.
Print to File Write a figure to a PostScript® file to
be printed later.
Export to File Export a figure in graphics format to a
file, so that you can import it into an
application.
Export to Clipboard Copy a figure to the Microsoft
Windows clipboard, so that you can
paster it into an application.
26
exporting it. You select each of these dialog boxes by clicking Size, Rendering,
Fonts, or Lines from the Properties list.
Adjusting the figure size Click Size in the Export Setup dialog box to
display this dialog box.
The Size dialog box modifies the size of the figure as it will appear when
imported from the export file into your application. If you leave the Width
and Height settings on auto, the figure remains the same size as it appears on
your screen. You can change the size of the figure by entering new values in
the Width and Height text boxes and then clicking Apply to Figure. To go
back to the original settings, click Restore Figure.
Adjusting the rendering Click Rendering in the Export Setup dialog box
to display this dialog box.
27
You can change the settings in this dialog box as follows.
• Colorspace. Use the drop-down list to select a colorspace. Your choices
are:
• Custom Color. Click the check box and enter a color to be used for the
figure background. Valid entries are:
• Custom Renderer. Click the check box and select a renderer from the
drop-down list:
• Resolution. You can select one of the following from the drop-down list:
28
– Screen — The same resolution as used on your screen display
– A specific numeric setting — 150, 300, or 600 dpi
– auto — UNIX selects a suitable setting
• Keep axis limits. Click the check box to keep axis tick marks and limits
as shown. If unchecked, automatically adjust depending on figure size.
• Show uicontrols. Click the check box to show all user interface controls
in the figure. If unchecked, hide user interface controls.
Changing font characteristics Click Fonts in the Export Setup dialog box
to display this dialog box.
• Custom Name. Click the check box and use the drop-down list to select
a font name from those offered in the drop-down list.
29
• Custom Weight. Click the check box and use the drop-down list to
select the weight or thickness to be applied to text in the figure. Choose
from normal, light, demi, or bold.
• Custom Angle. Click the check box and use the drop-down list to select
the angle to be applied to text in the figure. Choose from normal, italic,
or oblique.
Changing line characteristics Click Lines in the Export Setup dialog box
to display this dialog box.
Convert solid lines to cycle through line styles. When colored graphics
are imported into an application that does not support color, lines that could
formerly be distinguished by unique color are likely to appear the same. For
example, a red line that shows an input level and a blue line showing output
30
both appear as black when imported into an application that does not support
colored graphics. Clicking this check box causes exported lines to have different
line styles, such as solid, dotted, or dashed lines rather than differentiating
between lines based on color.
Saving and Loading Settings If you think you might use these export
settings at another time, you can save them now and reload them later. At
the bottom of each Export Setup dialog box, there is a panel labeled Export
Styles. To save your current export styles, type a name into the Save as style
named text box, and then click Save. If you then click the Load settings from
drop-down list, the name of the style you just saved appears among the choices
of export styles you can load. To load a style, select one of the choices from this
list and then click Load. To delete any style you no longer have use for, select
that style name from the Delete a style drop-down list and click Delete.
Exporting the figure When you finish setting the export style for your fig-
ure, you can export the figure to a file by clicking the Export button on the
right side of any of the four Export Setup dialog boxes. As new window labeled
Save As opens. Select a folder to save the file in from the Save in list at the
top. Select a file type for your file from the Save as type drop-down list at the
bottom, and then enter a file name in the File name text box. Click the Save
button to export the file.
where gcf is a function call that returns the handle of the current figure, and
each property value pair consists of a named property followed by the value to
which the property is set. For example,
31
sets the units of measure and the paper size.
The print function performs any of the four actions shown in the table
below. You control what action is taken, depending on the presence or absence
of certain arguments.
Action Print command
Print a figure to a printer print
Print a figure to a file for later printing print filename
Copy a figure in graphics format to the print -dfileformat
clipboard
Export a figure to a graphics format print -dfileformat filename
file that you can later import into an
application
You can also include optional arguments with the print command. For
example, to export Figure No. 2 to file spline2d.eps, with 600 dpi resolution,
and using the EPS color graphics format, use
32
Parameter Default print Command or set Property
Select figure Last active window print -fhandle
Select printer System default print -pprinter
Figure size 8-by-6 inches PaperSize (Figure),
PaperUnits (Figure)
Position on page 0.25 in. from left, 2.5 in. from PaperPosition (Figure),
bottom PaperUnits (Figure)
Position mode Manual PaperPositionMode (Figure)
Paper type Letter PaperType (Figure)
Paper orientation Portrait PaperOrientation (Figure)
Renderer Selected automatically print -zbuffer | -painters |
-opengl
Renderer mode Auto RendererMode (Figure)
Resolution Depends on driver or graphics print -rresolution
format
Axes tick marks Recompute XTickMode, etc. (Axes)
Background color Force to white Color (Figure),
InvertHardCopy (Figure)
Font size As in the figure FontSize (Text)
Bold font Regular font FontWeight (Text)
Line width As in the figure LineWidth (Line)
Line style Black or white LineStyle (Line)
Line and text color Black and white Color (Line, Text)
CMYK color RGB color print -cmyk
UI controls Printed print -noui
Bounding box Tight print -loose
Copy background Transparent See “Background color”
Copy size Same as screen size See “Figure Size”
33
radio buttons, list boxes, and sliders—just to name a few. GUIs created using
MATLAB tools can also perform any type of computation, read and write data
files, communicate with other GUIs, and display data as tables or as plots.
Most GUIs wait for their user to manipulate a control, and then respond to
each action in turn. Each control, and the GUI itself, has one or more user-
written routines (executable MATLAB code) known as callbacks, named for the
fact that they “call back” to MATLAB to ask it to do things. The execution of
each callback is triggered by a particular user action such as pressing a screen
button, clicking a mouse button, selecting a menu item, typing a string or a
numeric value, or passing the cursor over a component. The GUI then responds
to these events. You, as the creator of the GUI, provide callbacks which define
what the components do to handle events. This kind of programming is often
referred to as event-driven programming. In the example, a button click is one
such event. In event-driven programming, callback execution is asynchronous,
that is, it is triggered by events external to the software. In the case of MATLAB
GUIs, most events are user interactions with the GUI, but the GUI can respond
to other kinds of events as well, for example, the creation of a file or connecting
a device to the computer.
34
2.4 Creating a simple GUI with GUIDE
This section shows you how to create the graphical user interface (GUI) shown
in the following figure. using GUIDE.
>> guide
35
• In the Quick Start dialog, select the Blank GUI (Default) template. Click
OK to display the blank GUI in the Layout Editor, as shown in the fol-
lowing figure.
36
• Display the names of the GUI components in the component palette. Se-
lect Preferences from the MATLAB File menu. Then select GUIDE >
Show names in component palette, and click OK. The Layout Editor
then appears as shown in the following figure.
• Set the size of the GUI by resizing the grid area in the Layout Editor.
Click the lower-right corner and drag it until the GUI is approximately 3
inches high and 4 inches wide. If necessary, make the window larger.
37
• Add three push buttons, a static text area, a pop-up menu, and
an axes to the GUI. Select the corresponding entries from the component
palette at the left side of the Layout Editor and drag them into the layout
area. Position all controls approximately as shown in the following figure.
38
• If several components have the same parent, you can use the Alignment
Tool to align them to one another. To align the three push buttons:
1. Select all three push buttons by pressing Ctrl and clicking them.
2. Select Align Objects from the Tools menu to display the Align-
ment Tool.
3. Make these settings in the Alignment Tool, as shown in the following
figure:
– 20 pixels spacing between push buttons in the vertical direction.
– Left-aligned in the horizontal direction.
39
• Use the Alignment Tool to align and distribute all controls in the figure.
• The push buttons, pop-up menu, and static text have default labels when
you create them. Their text is generic, for example Push Button 1.
Change the text to be specific to your GUI, so that it explains what the
component is for.
• To change the text of the first Push Button:
40
• The pop-up menu provides a choice of three data sets: peaks, membrane,
and sinc. These data sets correspond to MATLAB functions of the same
name. To list those data sets as choices in the pop-menu:
41
• In this GUI, the static text serves as a label for the pop-up menu. The
user cannot change this text. This topic shows you how to change the
static text to read Select Data.
• In the Layout Editor, your GUI now looks like in the following figure, and
the next step is to save the layout.
42
• When you save a GUI, GUIDE creates two files, a FIG-file and a code file.
The FIG-file, with extension .fig, is a binary file that contains a descrip-
tion of the layout. The code file, with extension .m, contains MATLAB
functions that control the GUI.
• To save a GUI you can either choose Save as... from the File menu
or Run it (from the Tools menu). If you try to run an unsaved Figure,
GUIDE will ask you to save it first. Save the Figure as simpleGUI.fig (in
the current path): GUIDE saves the files simpleGUI.fig and simpleGUI.m.
The latter file is opened in the Editor.
• Run the figure by choosing Tools > Run or from the MATLAB console,
by typing:
>> simpleGUI
43
2.4.2 Adding code to the GUI
When you saved your GUI in the previous section, GUIDE created two files: a
FIG-file simpleGUI.fig that contains the GUI layout and a file, simpleGUI.m,
that contains the code that controls how the GUI behaves. The code consists
of a set of MATLAB functions (that is, it is not a script). But the GUI did not
respond because the functions contain no statements that perform actions yet.
Here we will see how to add code to the file to make the GUI do things.
Generating data to plot In this section we will learn how to generate the
data to be plotted when the GUI user clicks a button. The opening function
generates this data by calling MATLAB functions. The opening function,
which initializes a GUI when it opens, is the first callback in every GUIDE-
generated GUI code file. In this example, you add code that creates three data
sets to the opening function. The code uses the MATLAB functions peaks,
membrane, and sinc. Open simpleGUI.m in the Editor:
Make sure to leave the already esisting code after the lines you added.
The first six executable lines create the data using the MATLAB functions
peaks, membrane, and sinc. They store the data in the handles structure, an
argument provided to all callbacks. Callbacks for the push buttons can retrieve
the data from the handles structure.
The last two lines create a current data value and set it to peaks, and then
display the surf plot for peaks. The following figure shows how the GUI now
looks when it first displays.
44
Programming the popup menu The pop-up menu enables the user to
select the data to plot. When the GUI user selects one of the three plots, MAT-
LAB sets the pop-up menu Value property to the index of the selected string.
The pop-up menu callback reads the pop-up menu Value property to deter-
mine the item that the menu currently displays, and sets handles.current_data
accordingly.
It then uses a switch statement to make the selected data set the current
data. The last statement saves the changes to the handles structure.
45
switch str{val};
case ’Peaks’ % User selects peaks.
handles.current_data = handles.peaks;
case ’Membrane’ % User selects membrane.
handles.current_data = handles.membrane;
case ’Sinc’ % User selects sinc.
handles.current_data = handles.sinc;
end
% Save the handles structure.
guidata(hObject,handles)
Programming the push buttons Each of the push buttons creates a differ-
ent type of plot using the data specified by the current selection in the pop-up
menu. The push button callbacks get data from the handles structure and then
plot it.
• Right-click the Surf push button in the Layout Editor to display a context
menu. From that menu, select View Callbacks > Callback.
• This will display the pushbutton1_Callback() function in the Editor.
• Add the following code to the pushbutton1_Callback() after the comments:
• Repeat previous steps for the Mesh push button and add this code to the
pushbutton2_Callback():
• Repeat previous steps for the Contour push button and add this code to
the pushbutton3_Callback():
Running the GUI Run the GUI from the MATLAB console.
>> simpleGUI;
46
2.5.1 Creating a GUI code file
We will start by creating the backbone of our M-file. In the MATLAB console
type:
function simpleGUI2
% SIMPLEGUI2 Select a data set from the pop-up menu, then
% click one of the plot-type push buttons. Clicking the button
% plots the selected data in the axes.
end
The call to the figure function uses two property/value pairs. The Position
property is a four-element vector that specifies the location of the GUI on the
screen and its size: [distance from left, distance from bottom, width, height].
Add the previous code right after the initial comments in simpleGUI2.m.
Adding the components The example GUI has six components: three push
buttons, one static text, one pop-up menu, and one axes. Start by writing
statements that add these components to the GUI. Create the push buttons,
static text, and pop-up menu with the uicontrol function. Use the axes function
to create the axes.
• Add the three push buttons to your GUI by adding these statements to
your code file following the call to figure.
47
These statements use the uicontrol function to create the push buttons.
Each statement uses a series of property/value pairs to define a push but-
ton:
– Style — In the example, pushbutton specifies the component as a
push button.
– String — Specifies the label that appears on each push button. Here,
there are three types of plots: Surf, Mesh, Contour.
– Position — Uses a four-element vector to specify the location of each
push button within the GUI and its size: [distance from left, distance
from bottom, width, height]. Default units for push buttons are pixels.
Each call returns the handle of the component that is created (hsurf,
hmesh, hcontour ).
• Add the pop-up menu and its label to your GUI by adding these statements
to the code file following the push button definitions.
hpopup = uicontrol(’Style’,’popupmenu’,...
’String’,{’Peaks’,’Membrane’,’Sinc’},...
’Position’,[300,50,100,25]);
htext = uicontrol(’Style’,’text’,’String’,’Select Data’,...
’Position’,[325,90,60,15]);
For the pop-up menu, the String property uses a cell array to specify the
three items in the pop-up menu: Peaks, Membrane, Sinc. The static text
component serves as a label for the pop-up menu. Its String property
tells the GUI user to Select Data. Default units for these components are
pixels.
• Add the axes to the GUI by adding this statement to the code file. Set
the Units property to pixels so that it has the same units as the other
components.
ha = axes(’Units’,’pixels’,’Position’,[50,60,200,185]);
• Align all components except the axes along their centers with the following
statement. Add it to the code file following all the component definitions.
align([hsurf,hmesh,hcontour,htext,hpopup],’Center’,’None’);
• Make your GUI visible by adding this command following the align com-
mand.
set(f,’Visible’,’on’)
48
• This is what your code file should now look like:
function simpleGUI2
% SIMPLEGUI2 Select a data set from the pop-up menu, then
% click one of the plot-type push buttons. Clicking the button
% plots the selected data in the axes.
end
>> simpleGUI2
at the command line. This is what your GUI now looks like. Note that
you can select a data set in the pop-up menu and click the push buttons.
But nothing happens. This is because there is no code in the file to service
the pop-up menu or the buttons.
49
Initializing the GUI When you make the GUI visible, it should be initialized
so that it is ready for the user. This section shows you how to
1. Make the GUI behave properly when it is resized by changing the com-
ponent and figure units to normalized. This causes the components to
resize when the GUI is resized. Normalized units map the lower-left cor-
ner ofthefigurewindowto(0,0)andtheupper-rightcornerto(1.0, 1.0).
2. Generate the data to plot. The example needs three sets of data: peaks_data,
membrane_data, and sinc_data. Each set corresponds to one of the items
in the pop-up menu.
3. Create an initial plot in the axes
4. Assign the GUI a name that appears in the window title
5. Move the GUI to the center of the screen
6. Make the GUI visible
Replace this code in editor:
50
% Change units to normalized so components resize automatically.
set([f,hsurf,hmesh,hcontour,htext,hpopup],’Units’,’normalized’);
• Run your code by typing simpleGUI2 at the command line. The initializa-
tion above cause it to display the default peaks data with the surf function,
making the GUI look like this.
51
Programming the pop-up menu The pop-up menu enables users to select
the data to plot. When a GUI user selects one of the three data sets, MATLAB
sets the pop-up menu Value property to the index of the selected string. The
pop-up menu callback reads the pop-up menu Value property to determine
which item is currently displayed and sets current_data accordingly. Add the
following callback to your file following the initialization code and before the
final end statement.
Programming the push buttons Each of the three push buttons creates
a different type of plot using the data specified by the current selection in the
pop-up menu. The push button callbacks plot the data in current_data. They
automatically have access to current_data because they are nested at a lower
level. Add the following callbacks to your file following the pop-up menu callback
and before the final end statement.
52
function contourbutton_Callback(source,eventdata)
% Display contour plot of the currently selected data.
contour(current_data);
end
’Callback’,{@surfbutton_Callback}
hsurf = uicontrol(’Style’,’pushbutton’,’String’,’Surf’,...
’Position’,[315,220,70,25],...
’Callback’,{@surfbutton_Callback});
’Callback’,{@meshbutton_Callback}
• To the uicontrol statement that defines the Contour push button, add the
property/value pair
’Callback’,{@contourbutton_Callback}
• To the uicontrol statement that defines the pop-up menu, add the prop-
erty/value pair
’Callback’,{@popup_menu_Callback}
Running the GUI Run the GUI by typing the name of the code file at the
command line.
>> simpleGUI2
53
3 Object-oriented programming
3.1 References
• http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_oop/ug_intropage.html
• http://www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/matlab_oop.pdf
Classes and Objects A class describes a set of objects with common char-
acteristics. Objects are specific instances of a class. The values contained in an
object’s properties are what make an object different from other objects of the
same class (an object of class double might have a value of 5). The functions
defined by the class (called methods) are what implement object behaviors that
are common to all objects of a class (you can add two doubles regardless of their
values).
54
3.3 Classes in MATLAB
In the MATLAB language, every value is assigned to a class. For example,
creating a variable with an assignment statement constructs a variable of the
appropriate class:
>> a = 7;
>> b = ’some string’;
>> whos
Name Size Bytes Class
a 1x1 8 double
b 1x11 22 char
Basic commands like whos display the class of each value in the workspace. This
information helps MATLAB users recognize that some values are characters and
display as text while other values might be double, single, or other types of
numbers. Some variables can contain different classes of values like cells.
p1 + p2
the plus operation would know how to add polynomial objects because the
polynomial class defines this operation. When you define a class, you overload
special MATLAB functions (plus.m for the addition operator) that are called
by the MATLAB runtime when those operations are applied to an object of
your class.
55
• Events — Messages that are defined by classes and broadcast by class
instances when some specific action occurs
• Attributes — Values that modify the behavior of properties, methods,
events, and classes
• Packages — Folders that define a scope for class and function naming
56
3.7 Class folders
There are two basic ways to specify classes with respect to folders:
• Creating a single, self-contained class definition file in a folder on
the MATLAB path. The name of the file must match the class (and
constructor) name and must have the .m extension. The class is defined
entirely in this file.
• Distributing a class definition to multiple files in an @ folder inside a
path folder. Only one class can be defined in a @ folder.
In addition, package folders (which always begin with a “+” character) can
contain multiple class definitions, package-scoped functions, and other packages.
A package folder defines a new name space in which you can reuse class names.
Use the package name to refer to classes and functions defined in package folders
(for example, packagefld1.ClassNameA(), packagefld2.packageFunction()).
classdef className
...
end
The classdef block contains the class definition. The classdef line is where you
specify:
• Class attributes
Class attributes modify class behavior in some way. Assign values to class
attributes only when you want to change their default value. No change
to default attribute values:
classdef class_name
...
end
57
• Superclasses
To define a class in terms of one or more other classes by specifying the
superclasses on the classdef line:
A handle class inherits from the class handle (i.e. it has the class handle
as superclass):
The classdef block contains the properties, methods, and events subblocks.
classdef class_name
properties
PropertyName % No default value assigned
PropertyName = ’some text’;
PropertyName = sin(pi/12); % Expression returns default value
end
end
58
Evaluation of property default values occurs only when the value is first
needed, and only once when MATLAB first initializes the class. MATLAB
does not reevaluate the expression each time you create a class instance.
• In the class constructor — MATLAB evaluates the assignment expression
for each instance, which ensures that each instance has a unique value.
To assign values to a property from within the class constructor, reference
the object that the constructor returns (the output variable obj ):
classdef MyClass
properties
PropertyOne
end
methods
function obj = MyClass(intval)
obj.PropertyOne = intval;
end
end
end
All properties have attributes that modify certain aspects of the property’s
behavior. Specified attributes apply to all properties in a particular properties
block. For example:
classdef class_name
properties
PropertyName % No default value assigned
PropertyName = sin(pi/12); % Expression returns default value
end
properties (SetAccess = private, GetAccess = private)
Stress
Strain
end
end
In this case, only methods in the same class definition can modify and query the
Stress and Strain properties. This restriction exists because the class defines
these properties in a properties block with SetAccess and GetAccess attributes
set to private.
You can define methods that MATLAB calls whenever setting or querying
a property value. Define property set access or get access methods in methods
blocks that specify no attributes and have the following syntax:
methods
function value = get.PropertyName(object)
...
end
59
function obj = set.PropertyName(obj,value)
...
end
end
MATLAB does not call the property set access method when assigning the
default value specified in the property’s definition block. If a handle class defines
the property, the set access method does not need to return the modified object.
60
• Property access methods enable a class to define code to execute whenever
a property value is queried or set.
• Static methods are functions that are associated with a class, but do not
necessarily operate on class objects. These methods do not require an
instance of the class to be referenced during invocation of the method,
but typically perform operations in a way specific to the class.
• Conversion methods are overloaded constructor methods from other classes
that enable your class to convert its own objects to the class of the
overloaded constructor. For example, if your class implements a double
method, then this method is called instead of the double class constructor
to convert your class object to a MATLAB double object.
• Abstract methods serve to define a class that cannot be instantiated itself,
but serves as a way to define a common interface used by a number of
subclasses. Classes that contain abstract methods are often referred to as
interfaces.
The constructor method has the same name as the class and returns an object.
You can assign values to properties in the class constructor. Terminate all
method functions with an end statement.
classdef ClassName
methods
function obj = ClassName(arg1,arg2,...)
obj.Prop1 = arg1;
...
end
function normal_method(obj,arg1,...)
...
end
end
methods (Static = true)
function static_method(arg1,...)
...
end
end
end
MATLAB differs from languages like C++ and Java in that there is no special
hidden class instance (e.g. the this object) passed to all methods. You must
pass an object of the class explicitly to the method. The left most argument
does not need to be the class instance, and the argument list can have multiple
objects.
You can define class methods in files that are separate from the class def-
inition file. To use multiple files for a class definition, put the class files in a
folder having a name beginning with the @ character followed by the name of
61
the class. Ensure that the parent folder of the @-folder is on the MATLAB path.
To define a method in a separate file in the class @-folder, create the function
in a separate file, but do not use a method block in that file. Name the file with
the function name, as with any function.
You must put the following methods in the classdef file, not in separate files:
• Class constructor
• Delete method
• All functions that use dots in their names, including:
If you specify method attributes for a method that you define in a separate
file, include the method signature in a methods block in the classdef block. For
example, the following code shows a method with Access set to private in the
methods block. The method implementation resides in a separate file. Do not
include the function or end keywords in the methods block, just the function
signature showing input and output arguments.
classdef ClassName
% In a methods block, set the method attributes
% and add the function signature
methods (Access = private)
output = myFunc(obj,arg1,arg2)
end
end
classdef className
events
...
end
...
end
62
To define an event, you declare a name for the event in the events block. Then
one of the class methods triggers the event using the notify method, which is
method inherited from the handle class. Only classes derived from the handle
class can define events. For example, the following class:
• Defines an event named StateChange
• Triggers the event using the inherited notify method.
classdef class_name < handle % Subclass handle
events % Define an event called StateChange
StateChange
end
...
methods
function upDateGUI(obj)
...
% Broadcast notice that StateChange event has occurred
notify(obj,’StateChange’);
end
end
end
Any number of objects can be listening for the StateChange event to occur.
When notify executes, MATLAB calls all registered listener callbacks and passes
the handle of the object generating the event and an event structure to these
functions. To register a listener callback, use the addlistener method of the
handle class.
addlistener(event_obj,’StateChange’,@myCallback)
63
values only in cases where you want to change from the default value to another
predefined value.
64
The sections that follow describe the implementation of the methods illustrated
here, as well as some implementation details.
The coefficients are stored in the coef property of the DocPolynom class:
classdef DocPolynom
properties
coef
end
methods
function obj = DocPolynom(c)
% Construct a DocPolynom object using the coefficients supplied
...
65
Removing Irrelevant Coefficients MATLAB software represents polyno-
mials as row vectors containing coefficients ordered by descending powers. Zeros
in the coefficient vector represent terms that drop out of the polynomial. Lead-
ing zeros, therefore, can be ignored when forming the polynomial.
Some DocPolynom class methods use the length of the coefficient vector to
determine the degree of the polynomial. It is useful, therefore, to remove leading
zeros from the coefficient vector so that its length represents the true value.
The DocPolynom class stores the coefficient vector in a property that uses a
set method to remove leading zeros from the specified coefficients before setting
the property value.
p = DocPolynom([1 0 -2 -5])
p =
x^3 - 2*x -5
This statement creates an instance of the DocPolynom class with the specified
coefficients. Note how class methods display the equivalent polynomial using
MATLAB language syntax. The DocPolynom class implements this display
using the disp and char class methods.
66
The DocPolynom to Double Converter The double converter method for
the DocPolynom class simply returns the coefficient vector, which is a double
by definition:
function c = double(obj)
% DocPolynom/Double Converter
c = obj.coef;
end
p = DocPolynom([1 0 -2 -5])
the statement:
c = double(p)
returns:
c =
1 0 -2 -5
class(c)
ans =
double
67
s = cell(1,d);
ind = 1;
for a = obj.coef;
if a ~= 0;
if ind ~= 1
if a > 0
s(ind) = {’ + ’};
ind = ind + 1;
else
s(ind) = {’ - ’};
a = -a;
ind = ind + 1;
end
end
if a ~= 1 || d == 0
if a == -1
s(ind) = {’-’};
ind = ind + 1;
else
s(ind) = {num2str(a)};
ind = ind + 1;
if d > 0
s(ind) = {’*’};
ind = ind + 1;
end
end
end
if d >= 2
s(ind) = {[’x^’ int2str(d)]};
ind = ind + 1;
elseif d == 1
s(ind) = {’x’};
ind = ind + 1;
end
end
d = d - 1;
end
end
str = [s{:}];
end
p = DocPolynom([1 0 -2 -5]);
68
char(p)
ans =
x^3 - 2*x - 5
The value returned by char is a string that you can pass to eval after you have
defined a scalar value for x. For example: x = 3;
eval(char(p))
ans =
16
function disp(obj)
% DISP Display object in MATLAB syntax
c = char(obj);
if iscell(c)
disp([’ ’ c{:}])
else
disp(c)
end
end
The statement:
p = DocPolynom([1 0 -2 -5])
p =
x^3 - 2*x - 5
p + q
69
generates a call to a function @DocPolynom/plus.
The following function redefines the plus (+) operator for the DocPolynom
class:
function r = plus(obj1,obj2)
% Plus Implement obj1 + obj2 for DocPolynom
obj1 = DocPolynom(obj1);
obj2 = DocPolynom(obj2);
k = length(obj2.coef) - length(obj1.coef);
r = DocPolynom([zeros(1,k) obj1.coef]+[zeros(1,-k) obj2.coef]);
end
p + 1
function r = roots(obj)
% roots(obj) returns a vector containing the roots of obj
r = roots(obj.coef);
end
70
p = DocPolynom([1 0 -2 -5]);
then the statement:
roots(p)
gives the following answer:
ans =
2.0946
-1.0473 + 1.1359i
-1.0473 - 1.1359i
71
4.2 Java Virtual Machine (JVM)
Every installation of MATLAB software includes Java Virtual Machine (JVM)
software, so that you can use the Java interpreter via MATLAB commands, and
you can create and run programs that create and access Java objects5 .
The MATLAB Java interface enables you to:
• Access Java API (application programming interface) class packages that
support essential activities such as I/O and networking. For example, the
URL class provides convenient access to resources on the Internet.
• Access third-party Java classes
• Easily construct Java objects in MATLAB workspace
• Call Java object methods, using either Java or MATLAB syntax
which classpath.txt
To edit either the default file or the copy in your own directory, type:
edit classpath.txt
5 To
use a different JVM than the one that comes with MATLAB, you now can set the
MATLAB_JAVA system environment variable to the path of your JVM software.
72
4.3.2 Dynamic classpath
The dynamic class path can be loaded any time during a MATLAB software
session using the javaclasspath function. You can define the dynamic path (using
javaclasspath), modify the path (using javaaddpath and javarmpath), and refresh
the Java class definitions for all classes on the dynamic path (using clear with
the keyword java) without restarting MATLAB.
e:\java\classes\utilpkg.jar
A fully qualified name can be rather long, making commands and functions,
such as constructors, cumbersome to edit and to read. You can refer to classes
by the class name alone (without a package name) if you first import the fully
qualified name into MATLAB. The import command has the following forms:
MATLAB adds all classes that you import to a list called the import list. You
can see what classes are on that list by typing import, without any arguments.
Your code can refer to any class on the list by class name alone. When called
from a function, import adds the specified classes to the import list in effect for
that function.
73
4.5 Creating and using Java objects
You create a Java object in the MATLAB workspace by calling one of the con-
structors of that class. You then use commands and programming statements
to perform operations on these objects. You can also save your Java objects to
a MAT-file and, in subsequent sessions, reload them into MATLAB.
74
Tab key The simplest way is to type the name of a Java object on the MAT-
LAB console followed by ’.’ and press the Tab key.
A new window appears, listing one row of information for each method in the
class.
75
• Other (i.e. other relevant information): throws java.io.IOException, ...
• Inherited From (i.e. parent of the specified class): java.awt.MenuComponent,
...
methods class_name
methods class_name -full
n = methods(’class_name’)
n = methods(’class_name’,’-full’)
Use methods without the ’-full’ qualifier to return the names of all the methods
(including inherited methods) of the class. Names of overloaded methods are
listed only once. With the ’-full’ qualifier, methods returns a listing of the
method names (including inherited methods) along with attributes, argument
lists, and inheritance information on each. Each overloaded method is listed
separately.
For example, display a full description of all methods of the java.awt.Dimension
object.
76
base types defined for input arguments. Each row shows a MATLAB type fol-
lowed by the possible Java argument matches, from left to right in order of
closeness of the match. The MATLAB types (except cell arrays) can all be
scalar (1-by-1) arrays or matrices. All of the Java types can be scalar values or
arrays.
77
5 Interfacing with C/C++
5.1 References
• http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/f7667.html
• http://www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/apiext.pdf
78
• Assemble your functions and the MATLAB API functions into one or
more C/C++ source files.
• Write a gateway function in one of your C/C++ source files.
• Use the MATLAB mex function, called a build script, to build a binary
MEX-file.
• Use your binary MEX-file like any MATLAB function.
Options files control which compiler to use, the compiler and link command
options, and the runtime libraries to link against.
Using the ’mex -setup’ command selects an options file that is
placed in ~/.matlab/R2010a and used by default for ’mex’. An options
file in the current working directory or specified on the command line
overrides the default options file in ~/.matlab/R2010a.
To override the default options file, use the ’mex -f’ command
(see ’mex -help’ for more information).
The options files available for mex are:
1: /Applications/MATLAB_R2010a.app/bin/gccopts.sh :
Template Options file for building gcc MEX-files
2: /Applications/MATLAB_R2010a.app/bin/mexopts.sh :
Template Options file for building MEX-files via the system ANSI compiler
79
Now, MATLAB’s mex is configured to use the selected compiler to build your
MEX-files. We will discuss the Warning message from newer MATLAB versions
below.
arrayProduct(x,y,z,n)
from within your C program creates an array z with the values 7.5, 10, and 45.
The following steps show how to call this function in MATLAB, using a
MATLAB matrix, by creating the MEX-file arrayProduct.
#include "mex.h"
/* code here */
80
}7
mexFunction is the entry point for the MEX-file, i.e. what MATLAB will call
when launching your MEX-file. This is currently just a placeholder. We will
now add the content of the gateway function, but before that we will spend a
couple of words on the signature of mexFunction.
Input parameters (found in the prhs array) are read-only; do not modify them
in your MEX-file. Changing data in an input parameter can produce undesired
side effects.
The MATLAB language works with only a single object type: the MATLAB
array. All MATLAB variables, including scalars, vectors, matrices, strings, cell
arrays, structures, and objects, are stored as MATLAB arrays. In C/C++, the
MATLAB array is declared to be of type mxArray. The mxArray structure
contains, among other things:
• Its type
• Its dimensions
• The data associated with this array
• If numeric, whether the variable is real or complex
• If sparse, its indices and nonzero maximum elements
• If a structure or object, the number of fields and field names.
81
{
z[i] = x * y[i];
}
}
mwSize replaces int to ensure that mxArrays with more than 232 − 1 elements
can be addressed correctly.
82
5.5.5 Read input data
Put the following declaration statements at the beginning of your mexFunction:
If your source file is correct, mex should compile silently. In case something is
wrong, mex will output error messages to the MATLAB console.
83
Test the MEX-File Type:
s = 5;
A = [1.5, 2, 9];
B = arrayProduct(s,A)
B =
7.5000 10.0000 45.0000
s = 5;
A = [1.5, 2; 9 11];
B = arrayProduct(s,A)
s = 3
A = uint8( [1, 5, 9] );
B = arrayProduct(s,A)
84