Appendix B - MATLAB Refresher
Appendix B - MATLAB Refresher
Appendix B - MATLAB Refresher
B.1 Introduction
Attendees to our training courses typically have a various levels of experience working with MATLAB,
ranging from individuals that use it on a regular basis, to those who have not used it at all. For this reason,
we always start with a tutorial/refresher session to keep the audience on the same page—the goal of the
session is to provide the minimum amount of information to enable the MATLAB novice to navigate the
This need is greatly diminished in the context of this book, as the time-critical element of a one-week
course is not present. Once online resources are on the table, coupled with sufficient time to review them,
one can point to better and more comprehensive references, starting with MATLAB’s own online Help
Browser, as well as additional tutorials and guides available at the Mathworks website
www.mathworks.com/help.
Having said that, this appendix summarizes selected topics covered during the course MATLAB refresher.
Section B.2 reviews fundamentals such as mathematical operations and basic programming functionality.
Section B.3 focuses on non-numerical data constructs such as structures and cell arrays. Section B.4
reviews the basics of scripts and function m-files, and Section B.5 concludes with a cursory overview of
handle graphics and callbacks. Those concepts are illustrated with a simple graphical user interface (GUI)
example.
Throughout this Appendix, we use the Courier New font style to denote MATLAB expressions and
variables.
Page | 1
B.2 MATLAB Fundamentals
The MATLAB environment is highly flexible and fairly user-friendly. Upon opening the application, the
MATLAB “Desktop” window appears on the screen. The Desktop is itself a collection of different windows
that the user may customize to their individual preferences. An example is illustrated in Figure B.1. The
• The Command Window in the center is the main user interface. It features the command prompt (>>)
where the user enters line commands and executes scripts. Script m-files are executed by typing the
script name without the file extension. Calculation results and assorted system and error messages
• The Workspace window on the right displays the contents of the MATLAB base workspace, which
holds all the variables and data resulting from MATLAB calculations and programs.
Page | 2
• The Current Folder window on the left shows the contents of the folder that MATLAB currently points
to. The path to this folder is displayed in the address toolbar at the top. In the figure, the current
2022\Models. The Current Folder window is useful for accessing files and running scripts, among other
functions.
There are additional windows accessible through the “Layout” tab in the top Toolstrip. The location of the
windows themselves may be adjusted by simply dragging them with the mouse pointer. They may also be
set as separate, standalone windows—this is called “undocking” the window from the Desktop.
In its simplest application, MATLAB may be used to perform standard mathematical calculations; i.e., as a
numerical calculator. The user may type in an equation, hit “enter” on the keyboard, and the result will
show in the Command window. We note here that placing a semicolon at the end of the line before hitting
enter will suppress the output display; however, the calculation will still take place. The notation for math
operators is pretty standard and common to most high-level languages; they are shown in Table B.1.
Addition + 3+2=5
Subtraction - 3–2=1
Multiplication * 3*2=6
Division / 3 / 2 = 1.5
Power ^ 3^2 = 9
Page | 3
MATLAB is also a programming language, so the user may define variables and manipulate them as with
any other language. One useful MATLAB feature is the automatic expansion on the dimensionality of a
variable. Many high-level languages are very strict with the dimensionality of variables and vectors, and
their size must be defined before using them. In MATLAB, one may type something like
>> a = 2; (B.1)
>> a(2) = 5; (B.2)
When the first command is executed, ‘a’ is defined as a scalar variable. The second command
automatically expands ‘a’ into a two-element vector. This convenient behavior extends to vectors and
arrays or matrices. Examples of many of these features are shown by running the example script
MATLAB boasts an extensive library of functions, including trigonometric, linear algebra, logic, rounding,
and many other types. Complex numbers are supported, with the imaginary unit number denoted by
either “1j” or “1i”. The variables “i” and “j” may also be used, but their use is generally deprecated in
favor of the first two (“1j” and “1i”are reserved constants, while “i” and “j” may be overwritten).
MATLAB stands for “Matrix Laboratory” so naturally it supports linear algebra operations. Matrices or
arrays can be defined to an arbitrary number of dimensions. Examples of array notation and related
operations are demonstrated in the script “mat_examp2”, including the typical square bracket notation
[ ] used for vectors and matrices. MATLAB provides several utility functions that create specialized
matrices. A very useful function is “randn”, which is a random number generator for Gaussian (Normal)
distributed variables with zero mean and unit variance. Invoked by itself without any arguments, randn
returns a single random scalar; however when used with integer arguments it creates a matrix of
dimensions given by said arguments. For example, X = randn(5,10) is a matrix of 5 rows and 10
Page | 4
columns with Gaussian random variables as elements. Similarly, “rand” is the uniformly distributed (0,1)
So far we have used the terms ‘array’ and ‘matrix’ interchangeably, as they both refer to a
multidimensional collection of numerical values. The distinction between array and matrix operations is
very specific, however. Array operations in MATLAB are “element-by-element” operations. Assume one
>> C = A * B; (B.3)
N
C ( i, j )
= ∑ A ( i, n ) Β ( n, j )
n =1
(B.4)
for all values of i and j. If the user instead intends to multiply each element of “A” by its corresponding
element of “B”, this is an array operation and the proper syntax is
>> C = A .* B; (B.5)
This is equivalent to
for all values of i and j. Notice the period in front of the multiply operator in (B.5).
One useful application of array operations is the ability to “vectorize” code, which results in fewer lines of
code and run-time improvements—a win-win situation!
To illustrate, consider the receive power calculation from the radar range equation (covered in Chapter
2). Given all the equation parameters as N-element vectors, most languages would perform the
calculation in a for-loop construct similar to the following:
Page | 5
for n = 1:N
Pr(n) = Pt(n)*Gt(n)*Gr(n)*lambda(n)^2*sigma(n)/((4*pi)^3*R(n)^4);
end
where the expression inside the loop is executed N times. In MATLAB, the “vectorized” version looks as
follows:
Pr = Pt.*Gt.*Gr.*lambda.^2.*sigma./((4*pi)^3*R.^4); (B.7)
This line is executed once, and is orders of magnitude faster than the for-loop. This is demonstrated by
timing the execution duration of these lines using the utility functions tic and toc in the MATLAB script
“mat_examp5.”
B.3.1 Strings
Strings are arrays of characters. They are created using single quotes to distinguish them from variables.
>> a = b; (B.8)
“b” is a variable saved in a second variable “a”, while in
library functions for manipulating string variables. A few example operations with strings are
Cell arrays are generalized matrices. While elements of regular matrices are limited to numerical scalars,
elements of cell arrays—called “cells”—may contain any type of MATLAB variable of arbitrary
Page | 6
dimensionality, such as vectors, matrices, strings, other cell arrays, structures, etc. Cell arrays use curly
braces { } instead of square brackets like a numerical array. Syntax examples with the curly braces on
The expression in (B.10) creates a 1-by-3 cell array “C” consisting of a scalar, a string and a three-element
row vector. Note that C{3}(2) is a valid expression which returns the value 25.
The expression in (B.11) saves the value 15 in the cell located on the first row, third column of cell array
B.3.3 Structures
Structures are similar to cell arrays in that they are capable of holding dissimilar data types. Structures are
composed of identical records, and each record is composed of fields. Like a cell, structure fields may hold
just about any MATLAB expression: scalars constants or variables, vectors, matrices, strings, cell arrays,
creates a structure named “Quarterbacks” with a field called “Name” holding the string ‘Manning’.
The index (1) indicates this is the first record of the structure; if there is only one record, the index may
Page | 7
B.4 Scripts and Function m-files
All m-files are text files containing MATLAB commands. They are called “m-files” because of their .m file
extension. The two main types of m-files are scripts and functions. As mentioned earlier, scripts are
executed by typing their name in the Command window; there are also several alternate ways to run
scripts, such as right-clicking on the filename in the “Current Folder” window and selecting the “Run”
option from the drop-down menu. Scripts do not have explicit input or output arguments as functions do;
they operate on data available in the Workspace, and any data they create remains in the Workspace
Script files are created using the MATLAB editor, via the “New” option in the File section of the Toolstrip.
The editor may also be used to examine and make changes to existing files. The example script file
Notice in the example that the text is color-coded: Commands are black, and comments are in green.
Comments are created by adding a percent symbol (%); MATLAB ignores anything to the right of it on the
same line. Comments may be “in-line” to the right of a MATLAB command, or they may be in a separate
line by themselves. Function options such as the “on” and “off” settings following the “echo” function
Page | 8
Figure B.2 – Example script m-file displayed in the MATLAB editor.
The MATLAB editor also provides indications on the status of the code. The orange box at the top of the
right border indicates there are warnings about the code syntax. If there are syntax errors, the box turns
red; otherwise, it is green if there are no errors or warnings. The orange dashes running down the right
edge of the editor box indicate the line numbers where the warnings are located (red dashes for errors).
The user must hover the pointer above said dashes to see the location and read the warning or error
message. Furthermore, the lines of code themselves are highlighted in either orange or red at the location
of the warnings or errors, respectively. As an example, the orange highlight on lines 6 and 8 warn that the
products of those operations produce values that might be unused (this is because they are not saved to
any variable).
Page | 9
Functions are the second type of m-files. They are useful for extending the MATLAB language, as they are
treated exactly the same as library functions. An example function file is shown in Figure B.3, which mimics
This user-defined function “myabs” takes a single input argument “X” and returns a single output
argument “out”. The input may be multi-dimensional (notice the array notation in the power operators)
and may also be complex-valued. The first line in the file is the function definition, which includes the
keyword “function” color-coded in blue. The keyword “end” in the last line is actually optional.
One important reminder to avoid confusion is that the filename should match the name of the function
in the function definition line. MATLAB actually goes by the function filename, and not by what is in the
function definition line. If the function file in B.3 is renamed as “myabs2.m”, and the user attempts to call
the function as “myabs”, MATLAB will display a warning stating “Unrecognized function or
variable 'myabs.'”
Functions support the use of multiple input and output arguments, following the syntax
Page | 10
Notice the square brackets used for the output arguments. The m-file “mystats.m” is an example of a
MATLAB even supports functions with variable numbers of input and output arguments. The built-in cell
arrays “varargin” and “varargout” are variable length input and output argument lists, respectively.
The m-file script “vararg_examp1.m” shows an example of a function with variable input arguments.
It calls a function “plotpoints” that takes an arbitrary number of x-y values and creates a plot. The
function is called twice, first with six pairs of values, then a second time with four pairs. The code is shown
in Figure B.4.
Figure B.4 – Example function m-file with variable input arguments. Top: “vararg_examp1” first calls
“plotpoints” with six arguments, then with four. Bottom: Cell array “varargin” manages the
variable length argument list.
Page | 11
The built-in function “nargin” used in the for-loop inside “plotpoints” returns the length of
“varargin”, so it is six the first time the function is called, and four the second time.
“vararg_examp2.m.” This script calls the function “partialsums”, which calculates the N partial
sums of a vector of length N. The function is first called with N = 6, then a second time with N = 4. The
code is shown in Figure B.5. “nargout” returns the number of output arguments for each function call.
Figure B.5 – Example function m-file with variable output arguments. Top: “vararg_examp2” first
calls “partialsums” with six output arguments, then with four. Bottom: Cell array “varargout”
manages the variable length argument list.
Page | 12
B.5 Handle Graphics
One of MATLAB strengths is its powerful graphics. Creating plots to visualize data in multiple ways is easy
and convenient. The script “plot_examp” is a simple example showing the steps to create two-
Any graphics created in MATLAB, even a simple Cartesian plot, is composed of graphic “objects.” Each
object has a unique identifier called a “handle,” as well as a number of properties associated with it. For
example, each line in a plot is an object with properties such as the line width, the line type (solid, dashed,
etc.), the line color, etc. One easy way to access and modify these properties is through the Property
Editor, accessed via the Figure Toolbar. This is depicted in Figure B.6, using the plot resulting from running
“plot_examp.”
Figure B.6 – Accessing Property Inspector from Figure Toolbar is an easy way to change object properties
and customize the appearance of MATLAB graphics.
Graphic objects follow a hierarchy in which some objects are “children” of other objects that contain
them. Figure B.7 shows the object hierarchy corresponding to the figure depicted in figure B.6.
Page | 13
Figure B.7 – Object hierarchy of figure created by script “plot_examp.”
Instead of using the Property Editor, the user may also perform similar modifications via the command
line; while this approach is not as straightforward, it enables automation. The first step is to obtain the
handle of the object requiring modification. MATLAB offers many options for this. Often, the handle may
hf = figure; (B.14)
not only creates the usual figure window, but also returns the handle to the figure object, which in (B.14)
is stored in the variable “hf.” There are also utility functions available to obtain an object handle after
In the above definitions, “current” refers to the last object created, or the one last clicked with the mouse
pointer—meaning it is currently active. Other functions that may be used include “findobj” and
“findall.” The reader is referred to their online documentation for details on their usage, although an
Page | 14
Once the handle of the desired object is obtained, the user may modify a property using the function
Notice that the property name is specified as a string. Its value may be a string or a number, depending
on its type. A list of all user-modifiable properties associated with an object is obtained by using the “set”
One may also obtain property values using the function “get”, following the format
The script “plot_mods_examp” recreates the original figure from “plot_examp,” then steps through
using a series of “set” commands to modify its appearance such that it ends looking like the right side of
Figure B.8.
Figure B.8 – Results from “plot_mods_examp” to modify the original figure (left) using line
commands.
Page | 15
B.5.1 Graphical User Interfaces (GUIs) and Callbacks
GUIs allow Matlab users to input simulation parameters and otherwise interact with a MATLAB program
in an easy-to-use environment. The components of a GUI (buttons, checkboxes, etc.) are a special type of
graphics objects called “user interface control” or “uicontrol” objects. In principle, they are the same as
the graphic objects discussed in the previous section, in that they too have handles and properties
associated with them. Likewise, these properties may also be examined and modified using “get” and
“set”, respectively.
One important property associated with “uicontrol” objects is the “Callback” property. A
“Callback” is a specific action the GUI designer defines whenever the GUI operator activates a control
(i.e., presses a button, etc.). The “Callback” property then executes the Callback function associated
The following example of a simple GUI was created using MATLAB’s GUI Development Environment
(“GUIDE”). In a future MATLAB release, GUIDE will be replaced by the “App Designer,” which works very
2. The Quick Start looks as shown in Figure B.9. Click “OK” to select the default Blank GUI format.
Page | 16
Figure B.9 – The GUIDE Quick Start window.
The Blank GUI template consists of a gridded layout area and a component palette on the left side, as
depicted in Figure B.10.
Page | 17
3. Grab the GUI components from the palette by left-click and drag into the layout area. The GUI
example requires three “Push Button” objects, one “Check Box” and one “Axis” object. Place them
Figure B.11 – Left: GUI template with components laid out. Right: Property Inspector Window showing
the properties for the first (topmost) Push Button.
4. Select (click) the top Push Button object, then open the Property Inspector as shown on the right
side of Figure B.11. Change the following two properties to the indicated values:
5. Repeat step 4 for the middle and bottom Push Buttons, as well as for the Check Box, according to
the following:
b. Push Button 3: Change “String” to “Change Line Style”, and “Tag” to “changelinestyle”
Page | 18
6. Save the GUI figure as “simplegui.” GUIDE will automatically create an m-file called
“simplegui.m” and open it in the MATLAB editor. The code will look as shown in Figure B.12.
Figure B.12 – Two sections of “simplegui.m.” Top: Top portion of file, with comments warning the
user to avoid editing the initialization code. Bottom: Function definitions for a couple of Callback
functions serving as placeholders for the user.
Page | 19
The “simplegui.m” file is an example of a function m-file that holds multiple functions. The
function as the top of the file (that shares its name with the filename) is called the main function, and
all the subsequent functions are referred to as “subfunctions.” Subfunctions only exist in the scope of
the main function; i.e., they can only be called from the main function. Furthermore, notice the
subfunctions with “Callback” in their name are devoid of any code—they only have a function
definition line. These are placeholders for the user to add the desired actions. The first part of the
filename corresponds to the “Tag” property defined in step #5; so for example, the Callback function
7. The last step is to write the desired code in the Callback functions. When complete, it should look
The GUI is now ready for testing. Activate the GUI by typing
>> simplegui
in the MATLAB Command Window. The GUI window will appear, and the user may test it by pressing the
buttons, starting with “Plot Curve”. This example plots SNR in dB as a function of range in km. The final
Page | 20
Figure B.13 – Complete Callbacks for “simplegui” example.
Page | 21
Figure B.14 – Final result of “simplegui” example.
Summary
We reviewed a few selected concepts and features of the MATLAB programming environment. Many if
not most of the radar and EW models provided in this course use these features, so they will be seen
again. In particular, several models are GUI-driven. One particular issue not explored in this simple GUI
example is the sharing of data between different Callbacks. Two approaches to accomplishing this are
illustrated: The Radar Equation GUI in Chapter 2 uses Application Data (“app data”), while the Waveform
Page | 22