Appendix B - MATLAB Refresher

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

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

course examples successfully.

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

visible windows on this figure are the following:

Figure B.1 The MATLAB Desktop and commonly used windows.

• 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

and warnings are all displayed in the Command Window.

• 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

folder is C:\Users\cd137\Documents\Short Courses\M&S Radar Systems\M&S Radar Systems

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.

B.2.1 Calculations at the Command Line

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.

Table B.1 – Mathematical Operators in MATLAB


Operation Symbol Example

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

“mat_examp1” located in the “App B” folder.

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).

B.2.2 Matrices and Arrays

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)

random number generator function.

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

defines two N x N matrices “A” and “B”. The expression

>> C = A * B; (B.3)

refers to a matrix multiplication in the linear algebra sense. This is equivalent to

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

C(I,j) = A(I,j) * B(I,j) (B.6)

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 Strings, Cell Arrays and Structures

B.3.1 Strings
Strings are arrays of characters. They are created using single quotes to distinguish them from variables.

Thus, in the following expression:

>> a = b; (B.8)
“b” is a variable saved in a second variable “a”, while in

>> a = ‘b’ (B.9)


‘b’ is a string character saved in variable “a”. As is the case with numerical variables, there are many

library functions for manipulating string variables. A few example operations with strings are

demonstrated by running the script “string_examp.”

B.3.2 Cell Arrays

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

either side of the equal sign are as follows:

>> C = {10, ‘hello’, [ 15 25 35 ]}; (B.10)


>> A{1,3} = 15; (B.11)

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

“A”. Additional examples are demonstrated by running the script “cell_array_examp2.”

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,

other structures, etc.

As an example, the expression

Quarterbacks(1).Name = 'Manning'; (B.12)

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

be omitted. The script “struct_examp” develops this example further.

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

after completing execution.

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

“mat_examp1_wComments” as seen in the MATLAB editor is shown in Figure B.2.

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

in lines 3 and 23 are shown in magenta.

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

the absolute value MATLAB function “abs.”

Figure B.3 – Example function m-file displayed in the MATLAB editor.

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

[out1, out2, out3] = myfunction(input1,input2) (B.13)

Page | 10
Notice the square brackets used for the output arguments. The m-file “mystats.m” is an example of a

function with multiple inputs and outputs.

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.

Similarly, an example of variable output arguments using “varargout” is demonstrated by running

“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-

dimensional Cartesian plots and perform some basic formatting.

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

be obtained when the object is created; for example, the expression

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

creation. They include

• gcf – Returns handle of the current figure

• gca – Returns handle of current axes

• gco – A more general version which returns handle of current object

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

example of using “findobj” will be shown shortly.

Page | 14
Once the handle of the desired object is obtained, the user may modify a property using the function

“set” with the following format:

>> set(handle,’property_name’,value) (B.15)

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”

command with the object handle as its only argument:

>> set(handle) (B.16)

One may also obtain property values using the function “get”, following the format

>> value = get(handle,’property_name’) (B.15)

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

to it, which the designer must write.

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

similar. The steps to build the example GUI are as follows:

1. Open the GUIDE Quick Start window by typing

>> guide (B.16)

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.

Figure B.10 – Blank GUI template window.

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

and resize them as shown on the left side of Figure B.11.

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:

a. “String” – Change from “Push Button” to “Plot Curve”

b. “Tag” – Change from “pushbutton1” to “plotcurve”

5. Repeat step 4 for the middle and bottom Push Buttons, as well as for the Check Box, according to

the following:

a. Push Button 2: Change “String” to “Change Color”, and “Tag” to “changecolor”

b. Push Button 3: Change “String” to “Change Line Style”, and “Tag” to “changelinestyle”

c. Check Box: Change “String” to “Show Grid”, and “Tag” to “showgrid”

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

for the third Push Button is “changelinestyle_Callback,” as seen in the figure.

7. The last step is to write the desired code in the Callback functions. When complete, it should look

as shown in Figure B.13.

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

result should look like Figure B.14.

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

Generator GUI in Chapter 7 uses global variables.

The concept of Callbacks will be revisited in the Simulink tutorial.

Page | 22

You might also like