ENGINEERING SOFTWARE
EE 8207
LECTURE 2:
Visualization and Programming
in Matlab
Instructor: E.Tarimo Thursday, December 22, 2022
2022/2023
HOMEWORK 1 RECAP
Some things that came up:
Plotting a straight line
» x = 1:10
» plot (x, 0)
➢Not an error, but probably not what you meant
Use of semicolon – never required if one command per
line.
You can also put multiple commands on one line; in
this case, a semicolon is necessary to separate
commands:
» x = 1:10; y = (x-5).^2; z = x.*y;
Instructor: E.Tarimo Visualization and Programming 2022/2023
PLOTTING
Example
» x = linspace (0, 4*pi, 10);
» y = sin (x);
Plot values against their index
» plot (y);
Usually we want to plot y versus x
» plot (x, y); Matlab
makes
visualizing
data fun and
easy
Instructor: E.Tarimo Visualization and Programming 2022/2023
OUTLINE
(1) Functions
(2) Flow Control
(3) Line Plots
(4) Image/Surface Plots
(5) Efficient codes
(6) Debugging
Instructor: E.Tarimo Visualization and Programming 2022/2023
1. FUNCTIONS
Users can write functions which can be called from
the command line.
Functions can accept input variable(s)/matrice(s) and
will output variable(s)/matrice(s).
Functions will not manipulate variable(s)/matrice(s)
in the Matlab Workspace.
In Matlab functions closely resemble scripts and can
be written in the Matlab editor.
Matlab functions have the function keyword.
Instructor: E.Tarimo Visualization and Programming 2022/2023
1. FUNCTIONS
Remember that the filename of a function will be its
calling function name.
Don’t overload any built-in functions by using the
same filename for your functions or scripts!
Functions can be opened for editing using the open
command.
Many built-in Matlab functions can also be viewed
using this command.
Instructor: E.Tarimo Visualization and Programming 2022/2023
USER-DEFINED FUNCTIONS
Functions look exactly like scripts, but for ONE
difference
➢Functions must have a function declaration
function output = funName (input)
Must have the
Function name should
reserved
match m-file name
word: function
Instructor: E.Tarimo Visualization and Programming 2022/2023
output function name input
function keyword
help lines
for function Make sure you save changes to the
m-file before you call the function
for
statement
block Call the function iterate
in command window
Access the comments of
your Matlab functions
>> help iterate
Instructor: E.Tarimo Visualization and Programming 2022/2023
USER-DEFINED FUNCTIONS
Some comments about the function declaration
Instructor: E.Tarimo Visualization and Programming 2022/2023
USER-DEFINED FUNCTIONS
Some comments about the function declaration
No need for return: MATLAB 'returns' the variables
whose names match those in the function declaration
(though, you can use return to break and go back to
invoking function)
Variable scope: Any variable created within the
function but not returned disappears after the
function stops running (They’re called “local
variables”)
Instructor: E.Tarimo Visualization and Programming 2022/2023
FUNCTIONS: OVERLOADING
We're familiar with
» zeros
» size
» length
» size
Look at the help file for size by typing
» help size
The help file describes several ways to invoke the function
➢d = size(x)
➢[m,n] = size(x)
➢[m1,m2,m3,...,mn] = size(x)
➢m = size(x,dim)
Instructor: E.Tarimo Visualization and Programming 2022/2023
FUNCTIONS: OVERLOADING
MATLAB functions are generally overloaded
➢Can take a variable number of inputs
➢Can return a variable number of outputs
What would the following commands return:
» a=zeros(2,4,8);%n-dimensional matrices are ok
» D = size(a)
» [m, n] = size(a)
» [x, y, z] = size(a)
» m2 = size(a,2)
You can overload your own functions by having variable
number of input and output arguments
(see varargin,nargin,varargout, nargout)
Instructor: E.Tarimo Visualization and Programming 2022/2023
FUNCTIONS: EXERCISE
Write a function with the following declaration:
function plotSin(f1)
In the function, plot a sine wave with frequency f1, on
the interval [0,2π]:
To get good sampling, use 16 points per period.
Instructor: E.Tarimo Visualization and Programming 2022/2023
2. FLOW CONTROL
RELATIONAL OPERATORS
MATLAB uses mostly standard relational operators
➢equal ==
➢not equal ~=
➢greater than >
➢less than <
➢greater or equal >=
➢less or equal <=
Logical operators elementwise short-circuit (scalars)
➢And & &&
➢Or | ||
➢Not ~
➢Xor xor
➢All true all
➢Any true any
Boolean values: zero is false, nonzero is true
See help. for a detailed list of operators
Instructor: E.Tarimo Visualization and Programming 2022/2023
Functions can have many
outputs contained in a matrix
if statement block
Instructor: E.Tarimo Visualization and Programming 2022/2023
if/else/elseif
Basic flow-control, common to all languages
MATLAB syntax is somewhat unique
No need for parentheses: command blocks are between
reserved words
Lots of elseif ? consider using switch
Instructor: E.Tarimo Visualization and Programming 2022/2023
Instructor: E.Tarimo Visualization and Programming 2022/2023
for
for loops: use for a known number of iterations
MATLAB syntax:
The loop variable
➢Is defined as a vector
➢Is a scalar within the command block
➢Does not have to have consecutive values (but
it's usually cleaner if they're consecutive)
The command block
➢Anything between the for line and the end
Instructor: E.Tarimo Visualization and Programming 2022/2023
for
Instructor: E.Tarimo Visualization and Programming 2022/2023
while
The while is like a more general for loop:
➢No need to know number of iterations
The command block will execute while the conditional
expression is true
Beware of infinite loops!
You can use break to exit a loop
Instructor: E.Tarimo Visualization and Programming 2022/2023
while
Instructor: E.Tarimo Visualization and Programming 2022/2023
EXERCISE: CONDITIONALS
Modify your function plotSin(f1) function to take two
inputs: function plotSin(f1,f2)
If the number of input arguments is 1, execute the plot
command you wrote before. Otherwise, display the line
‘two inputs were given’
Hint: the number of input arguments is stored in the built-
in variable nargin
Instructor: E.Tarimo Visualization and Programming 2022/2023
3. LINE PLOTS
PLOT OPTIONS
Can change the line color, marker style, and line style
by adding a string argument
Can plot without connecting the dots by omitting line
style argument
Look at help plot for a full list of colors, markers, and
line styles
Instructor: E.Tarimo Visualization and Programming 2022/2023
to select lines
and delete or
change
PLAYING WITH THE PLOT properties
Insert legend
Instructor: E.Tarimo Visualization and Programming 2022/2023
PLAYING WITH THE PLOT
Instructor: E.Tarimo Visualization and Programming 2022/2023
PLAYING WITH THE PLOT
Instructor: E.Tarimo Visualization and Programming 2022/2023
LINE AND MARKER OPTIONS
See doc line_props for a
full list of properties that
can be specified
Instructor: E.Tarimo Visualization and Programming 2022/2023
CARTESIAN PLOTS
We have already seen the plot function
The same syntax applies for semilog and loglog plots
For example:
Instructor: E.Tarimo Visualization and Programming 2022/2023
3D LINE PLOTS
We can plot in 3 dimensions just as easily as in 2D
Instructor: E.Tarimo Visualization and Programming 2022/2023
3D LINE PLOTS
We can plot in 3 dimensions just as easily as in 2D
Use tools on figure to rotate it.
Can set limits on all 3 axes
Instructor: E.Tarimo Visualization and Programming 2022/2023
AXIS MODES
Built-in axis modes (see doc axis for more modes)
» axis square
➢makes the current axis look like a square box
» axis tight
➢fits axes to data
» axis equal
➢makes x and y scales the same
» axis xy
➢puts the origin in the lower left corner (default for
plots)
» axis ij
➢puts the origin in the upper left corner (default for
matrices/images)
Instructor: E.Tarimo Visualization and Programming 2022/2023
MULTIPLE PLOTS IN ONE FIGURE
To have multiple axes in one figure
» subplot (2, 3, 1)
➢makes a figure with 2 rows and 3 columns of axes, and
activates the first axis for plotting
➢each axis can have labels, a legend, and a title
» subplot (2, 3, 4:6)
➢activates a range of axes and fuses them into one
To close existing figures
» close ([1 3])
➢closes figures 1 and 3
» close all
➢closes all figures (useful in scripts)
Instructor: E.Tarimo Visualization and Programming 2022/2023
ADVANCED PLOTTING: EXERCISE
Modify the plot command in your plotSin function to
use squares as markers and a dashed red line of
thickness 2 as the line. Set the marker face color to
be black (properties are )
If there are 2 inputs, open a new figure with 2 axes,
one on top of the other (not side by side), and plot both
frequencies (subplot)
Instructor: E.Tarimo Visualization and Programming 2022/2023
4. IMAGE/SURFACE PLOTS
VISUALIZING MATRICES
Any matrix can be visualized as an image
imagesc automatically scales the values to span the
entire colormap
Can set limits for the color axis (analogous to xlim,
ylim)
Instructor: E.Tarimo Visualization and Programming 2022/2023
COLORMAPS
You can change the colormap:
See help hot a list
Can define custom
color-map
Instructor: E.Tarimo Visualization and Programming 2022/2023
SURFACE PLOTS
It is more common to visualize surfaces in 3D
Example:
surf puts vertices at specified points in space x,y,z, and
connects all the vertices to make a surface
The vertices can be denoted by matrices X,Y,Z
How can we make these matrices
➢built-in function: meshgrid
[X,Y] = meshgrid(x,y) transforms the domain specified by vectors x
and y into arrays X and Y
Instructor: E.Tarimo Visualization and Programming 2022/2023
surf
Make the x and y vectors
Use meshgrid to make matrices
To get function values,
evaluate the matrices
Plot the surface
*Try typing surf(membrane)
Instructor: E.Tarimo Visualization and Programming 2022/2023
surf Options
See help surf for more options
There are three types of
surface shading
You can also change the
colormap
Instructor: E.Tarimo Visualization and Programming 2022/2023
contour
You can make surfaces two-
dimensional by using contour
➢takes same arguments as surf
➢color indicates height
➢can modify linestyle properties
➢can set colormap
Instructor: E.Tarimo Visualization and Programming 2022/2023
EXERCISE: 3-D PLOTS
Modify plotSin to do the following:
If two inputs are given, evaluate the following function:
y should be just like x, but using f2. (use meshgrid
to get the X and Y matrices)
In the top axis of your subplot, display an image of
the Z matrix.
Display the color bar and use hot a colormap.
Set the axis to xy (imagesc, colormap, colorbar, axis)
In the bottom axis of the subplot, plot the 3-D surface of
Z(surf).
Instructor: E.Tarimo Visualization and Programming 2022/2023
EXERCISE: 3-D PLOTS
Instructor: E.Tarimo Visualization and Programming 2022/2023
5. EFFICIENT CODES
find
find is a very important function
➢Returns indices of nonzero values
➢Can simplify code and help avoid loops
Basic syntax: index = find(cond)
inds contains the indices at which x has values between
0.4 and 0.6.
This is what happens:
x>0.4 returns a vector with 1 where true and 0 where false
x<0.6 returns a similar vector
& combines the two vectors using logical and operator
find returns the indices of the 1's
Instructor: E.Tarimo Visualization and Programming 2022/2023
Example: Avoiding Loops
Given x = sin(linspace(0,10*pi,100)), how many of the
entries are positive?
Avoid loops!
Built-in functions will make it faster to write and
execute
Instructor: E.Tarimo Visualization and Programming 2022/2023
Vectorization
Avoid loops
➢This is referred to as vectorization
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
For instance, to add every two consecutive terms:
Instructor: E.Tarimo Visualization and Programming 2022/2023
Vectorization
Avoid variables growing inside a loop
Re-allocation of memory is time consuming
Pre allocate the required memory by initializing the
array to a default value
For example:
Instructor: E.Tarimo Visualization and Programming 2022/2023
Vectorization
Avoid variables growing inside a loop
Re-allocation of memory is time consuming
Pre allocate the required memory by initializing the
array to a default value
For example:
Instructor: E.Tarimo Visualization and Programming 2022/2023
6. DEBUGGING
Display
Instructor: E.Tarimo Visualization and Programming 2022/2023
Debugging
To use the debugger, set breakpoints
➢Click on – next to line numbers in m-files
➢Each red dot that appears is a breakpoint
➢Run the program
➢The program pauses when it reaches a breakpoint
➢Use the command window to probe variables
➢Use the debugging buttons to control debugger
Instructor: E.Tarimo Visualization and Programming 2022/2023