Topics Overview
Course Handout: (last update Wednesday, 17-Oct-2007 12:53:58 EDT)
These notes may be found at http://www.dartmouth.edu/~rc/classes/matlab_prog. The online version has many links to additional information and may be more up to date than the printed notes
Matlab
Programming
Topics Overview
- Data types (matrices, ND arrays, string arrays, cell arrays,
structures)
- Flow Control and Array Operations
- Performance Considerations
- Different Kinds of Functions
- Variables and Workspaces
- Graphics and graphics handles
- Importing/Exporting Data
- Visual Debugging
- Profiling
Click here
to download the examples used in the class.
Slides for Intro to Matlab class are here.
Table of Contents
(1)
Types of Program Files
M-files : ASCII text files that
contain sequences of matlab commands (.m file extension)
2 kinds of M-files:
- script files - automate long sequences of commands
- function files - extend matlab by developing new commands
Can be created in matlab editor or an editor of your choice
(2)
The
Matlab Path
- MATLAB Path
- List of directories searched by Matlab (includes /toolbox)
- Path Cache
- List of /toolbox files and locations
- Created at start to increase speed
- Working With the Path
- Path browser (pathtool)
- commands: path,addpath,rmpath
try:
path
pathtool
(3)
Matlab Data Types
Default Numeric Data Type - double
(4)
Defining Numerical Matrices
Square Brackets
- a comma or space indicates a separate entry in the same row
- a semicolon indicates the end of a row
Use of Colons
- use colons to define numeric sequences
- sequences are linearly space monotonically increasing or
decreasing
- sequence = min:step:max
- sequence = min:max ( assumes a step of 1)
Parentheses
- Used to reference individual elements (row,column)
Try:
>> x=[1 5; 10 15]
x =
1 5
10 15
>> y = [ 4,5,6; 7,8,9]
y =
4 5 6
7 8 9
>> z= [ .4 cos(pi/3) 6/7^2]
z =
0.400 0.500
0.1224
>> z(2,3) =.9
z =
0.400 0.500
0.1224
0
0 0.9000
Try:
>> t= 0:2:10
t =
0 2 4 6 8 10
>>v =20:25
v =
20 21 22 23 24 25
(5)
Matlab Multidimensional Arrays:
- arrays with more than 2 subscripts
Examples:
- 3D physical data
- sequence of matrices
- samples of a time-dependent 2D or 3D data
To make multidimensional array:
>> a = [2 4 6; 7 8 9; 1 2 3]
>> a(:,:,2)= [10 11 12; 0 1 2; 4 5 6]
When you add elements and expand the size
Unspecified elements are set to zero
>> a(:,:,4) = [ 1 1 1; 2 2 2; 3 3 3]
(6)
String Arrays
- created using single quotes
- stored as row vectors and takes 2 bytes per character
- use [,] to concatenate strings
- use [;] to vertically concatenate strings (must be of equal
length)
- use strvcat to vertically concatenate strings arrays of non-equal
length
Try:
str1='Hi there. '
str2='How are you?'
str3= 'Bye'
c1= [str1,' ',str2] % join two strings
c2 = [str1;str2] % vertical concatenation (must be same length)
c3=strvcat(str1,str2,str3) % vertically concatenate (matrix)
(7)
Cell Arrays
- A cell array is a general purpose matrix
- Each of the elements can contain data of a different type, size
and dimension
- Cell arrays are created using the cell command or by
using curly braces
- >> cell_name{row,col} = data;
- Storage is allocated dynamically
- cellplot shows a graphical depiction of a cell array
Try:
>>
A= {rand(2,2,2), ' February', 10.28}
A =
[2x2x2 double] 'February', [10.2800]
B{1,1}=1:8;
B{1,2}=strvcat('Monday','Tuesday','Wednesday','Thursday');
B{2,2}=A;
B{1,1}
A{1,1}(2,:,1)
cellplot(B)

(8)
Structures
- Structures are multidimensional arrays
- Elements are accessed by named fields
- Fields can contain any type of data
- Syntax is similar to C
- Storage is allocated dynamically
Syntax:
>> struct_name(record #).field_name=data
Try:
students.name = 'Sally';
students.grades= [97 93 ];
students(2).name = 'John';
students(2).grades= [94 96 ];
or
students= struct('name',{'Sally','John'},'grades',{[97 93], [94 96]});
students(1).name
students.grades
(9)
Boolean Operators
- functions that test the validity of a statement
- if TRUE returns 1
- if FALSE returns 0
Operator
|
Meaning
|
==
|
equal to
|
~
|
not
|
~=
|
not equal to
|
>
|
greater than
|
>=
|
greater than or equal to
|
<
|
less than
|
<=
|
less than or equal to
|
&
|
and
|
|
|
or
|
isfinite()
|
returns true if finite
|
any()
|
returns true if any element is nonzero
|
all()
|
returns true if all elements are nonzero
|
isinf()
|
returns true if infinite
|
isnan()
|
returns true if NaN (not a number)
|
Try:
>> a==6;
>> a>0
>> a~=5
>> b= [ -5 8 Inf 50 NaN 0]
>> b< 3
>> isfinite(b)
>> all(b)
>> isnan(b)
>> bool_ops
(10)
Logic Control Constructs
- Logic Control
- if/elseif/else
- switch/case/otherwise
- Iterative Loops
try:
x=34;
y=26;
if x>y
z=1
elseif x==y
z=0
else
z=-1
end
month ='april';
switch month
case{ 'january' 'march' 'may' 'july' 'august' 'october' 'december'}
days=31
case { 'april' 'june' 'september' 'november' }
days =30
case {'february' }
days=28
otherwise
days=-1
end
(11)
For and While Loops
- Similar to other programming languages
- For - repeats loop a number of times based on index value
- While - repeats loop until logical condition returns false
- Can be nested
try:
a=100
for i=1:a
for j=1:a
x(i,j)=i^2+3*j +1;
end
end
done=false;
max=1300;
i=1;
while(~done)
y(i)= i^3*2+1
if y(i) >max
done=true;
end
i=i+1
end
(12)
Performance
Increase - Vectorization
- Matlab is designed to work with matrices
- Can use array operations instead of using loops
Example Using Loops (what you do in most programming languages)
m=rand(5,1000); l=rand(5,1000);
w=rand(5,1000); h=rand(5,1000);
[rows,cols] =size(m);
for i= 1:rows
for j=1:cols
density(i,j)=m(i,j)/(l(i,j)*w(i,j)*h(i,j));
end
end
Example Using Array Operations
m=rand(5,1000); l=rand(5,1000);
w=rand(5,1000); h=rand(5,1000);
density=m./(l.*w.*h);
Example: array_vs_loops
(13)
Performance Increase - Preallocation
Preallocation of Variables creates a contiguous memory space at the
start
Otherwise matlab creates different size memory blocks at each step
Preallocation example:
% Use preallocation
pre_alloc = zeros(1000,1);
for i=1,1000
pre_alloc(i)=rand(1);
end
% No preallocation:
for i=1,1000
not_pre_alloc(i)=rand(1);
end
try:
>> pre_allocate
(14)
Load and Save Functions
Commands load and save
- assume data is stored in a platform-independent binary format
- default filename is matlab.mat
- file name ends in a .mat extension
- read/write binary data files by default
save
save filename
save filename x y z
load filename data*
save filename -ascii
load
load filename
load filename x y z
load filename data*
load filename
Try:
>>clear
a= rand(3,2);
b=ones(3,2);
c = a.^2+b;
save mydata
clear
load mydata
save -ascii mydata_ascii
clear
load mydata_ascii
(15)
Importing Data Into Matlab
- importdata command
- uses file extension if possible to determine file type
- if no recognizable file extension, assumes delimited data
- file type determines data type
- uiimport command
- GUI interface to import data
- textscan command
- imports to cell arrays
- use for non-standard data formats and large files
try:
help iofun
help fileformats
uiimport
mydata=importdata('Sample_Data_File.txt')
textscan_example
%
textscan_example.m - example of using textscan command to
import data
fid=fopen('Sample_Data_File.txt');
numCols=10;
numHeaders=1;
format1=repmat('%s ',1,numCols);
format2=repmat('%d ',1,numCols-1);
format2=['%s ' format2];
myHeader=textscan(fid,format1,1);
myData=textscan(fid,format2);
fclose(fid);
disp('here are the first 5
elements from column 1 (not including the header row');
myData{1,1}(1:5)
disp('here are the 10 elements
from column 9 (not including the header row');
myData{1,9}(1:10)
disp('here are the first 8
columns in the header row');
myHeader{1,1:8}
(16)
Functions
- Core MATLAB (built-in) functions
- MATLAB-supplied M-file functions
- User-created M-file functions
Differences between Script and Function
M-Files
- Structural syntax
- Functions workspace, inputs and outputs
(17)
Workspaces In Matlab
- Matlab (or base) workspace
- for command line and script variables
- Function workspaces
- Each function has its own workspace
- Communicate to function workspace via inputs and outputs
- Prevents name conflicts
- Global workspace
- Global variables can be shared by multiple workspaces
- Must be initialized in all relevant workspaces
- Functions related to workspaces
- mlock - prevent m-file from being cleared
- munlock- allow m-file to be cleared
- persistent -persistent variables keep their value
from one function call to another
- global - initialize global variables in source
workspace first
(18)
Structure of a Function M-File
Example of a function:
function y = mymean(x)
%MYMEAN Average or mean value.
% For vectors, MYMEAN(X) is the mean value of the
elements in X. For
% matrices, MYMEAN(X)is a row vector
containing the mean value of
% each column. For N-D arrays, MYMEAN(X) is the mean
value of the
% elements along the first non-singleton dimension of X.
[m,n]=size(x);
if m==1
m=n;
end
y=sum(x)/m;
Required
- Keyword: function
- Function name (same as the file name)
- File has a *.m extension
- Results must be stored in variable(s) with the same name as the
output arguments
Optional
- Input/Output Arguments - these define the internal variable names
- Online help- comment lines following the function definition line
- the lookfor command uses the first comment line
in its search
- Matlab code -contains the matlab expressions to be executed
Command Line Syntax
- matlab searches the path for an m-file with the specified
function name
Try:
>> a=rand(5);
>> b=mymean(a)
(19)
Multiple Inputs and Outputs for a
Function
function [avg,stdev,r] = ourstats(x,tol)
%OURSTATS finds the average, standard deviation and rank of a matrix
[m,n]=size(x)
if m==1;
m=n;
avg=sum(x)/mean;
stdev=sqrt(sum(x.^2)/m - avg.^2);
s=svd(x);
r=sum(s>tol);
A function can have multiple inputs/outputs
- nargin - number of function input arguments
- nargout - number of function output arguments
>>
[a,s,rank]=ourstats(1:99,0.1);
(20)
Exercise - Write a function M-file
Write a function that has three lengths for its inputs and outputs a
string that says if a triangle can or cannot be formed from the lengths
provided.
Extra credit: indicate if the triangle is scalene, isosceles
or equilateral
Note: A triangle can only be formed if the sum of the two
shorter sides is less than the longest side.
(21)
Sample Answer - Determine if 3
numbers form the sides of a triangle
function str_tri_test =
istriangle(a,b,c)
% istriangle determine if a,b,c form a triangle
v =[ a b c];
vsort=sort(v);
if vsort(1) + vsort(2) > vsort(3)
s1=['The sides ',num2str(v),' form a triangle.'];
% start extra credit
if (a==b) & (b==c) % all sides equal
s2=' The triangle is an
equialateral triangle.';
elseif (a==b) |(b==c) |(a==c)
s2= ' The triangle is an
isosceles triangle.';
else
s2= ' The triangle is a
scalene triangle.';
end
%end extra credit
str_tri_test=strcat(s1,s2);
else
str_tri_test= ['The sides ',num2str(v),' do not form
a triangle.'];
end
try:
>> istriangle(3,4,5)
(22)
Types of Matlab Functions
- Subfunctions
- contained in m-file of a primary function
- callable only by primary functions and other subfunctions in
that file
- does not share workspace of the primary function
- Private Functions
- reside in subdirectory with special name private
- visible only to functions in the parent directory
- useful when overriding another function with the same name
- Nested Functions
- defined within the body of another function
- has its own workspace
- has access to the workspace of the function(s) that it is
nested within
- Function Handles
- used in calling functions indirectly
- often used when passing a function name as an input to another
function
- handle= @functionname
- Anonymous Functions
- simple function which does not require an M-file
- single matlab expression with inputs and outputs
- f = @(arglist) expression
(23)
Anonymous Function Example
@ operator creates a function
handle
try:
f=@(x)(sin(x)+cos(x));
f(2)
function ode_ex1
xstart =0;
xfinal =7;
xrange=xstart:.2: xfinal;
y0=1;
dydx=@(x,y) x+y;
[x,y]=ode45(dydx,xrange,[y0]);
ya= 2*exp(xrange)-xrange-1;
plot(x,y,'r',x,ya,'+');
try:
>> ode_ex1
(24)
Subfunction and Function
Handle Example
function ode_ex2
tstart
=0;
tfinal =20;
trange=[tstart tfinal];
y0=[2;0]; % inital conds
y(0)=2, dy/dt((0)=0
options =
odeset('RelTol',1e-4,'AbsTol',[1e-4 1e-4]);
[t,y]=ode45(@vdpol,trange,y0,options);
plot(t,y(:,1),t,y(:,2),'r');
legend('y','dy/dt');
% define differential
equation function
% solve van der Pol equation
% d^2y/dt^2 = mu*(1-y^2)*dy/dt-y
function
dy=vdpol(t,y)
mu=2;
dy=zeros(2,1);
dy(1)=y(2);
dy(2)=mu*(1-y(1)^2)*y(2)-y(1);
try:
>> ode_ex2
(25)
Nested Function and Function
Handle Example
Find a zero of a cubic polynomial x^3+b*x+c for different values of b
and c near x0.
Try:
function y =
findzero(b, c, x0)
options = optimset('Display',
'off'); % Turn off Display
y = fzero(@poly, x0, options);
function y =
poly(x) % Compute the polynomial.
y = x^3 + b*x
+ c;
end
end
x = findzero(2, 3.5, 0)
(26)
Tips on Using Global Variables
- Use unique descriptive names for global variables
- all functions use the same global workspace
- whos global
- shows the contents of the global workspace
- clear global
- clears the global workspace
- isglobal(variable_name)
- test to see if a variable is global
Example:
function tic
% TIC Start a
stopwatch timer.
%
TIC; any stuff; TOC
% prints the
time required.
% See also:
TOC, CLOCK.
global TICTOC
TICTOC = clock;
function t =
toc
% TOC Read the
stopwatch timer.
% TOC prints
the elapsed time since TIC was used.
% t = TOC;
saves elapsed time in t, does not print.
% See also:
TIC, ETIME.
global TICTOC
if nargout < 1
elapsed_time =
etime(clock, TICTOC)
else
t =
etime(clock, TICTOC);
end
(27)
MATLAB Calling Priority
In order of priority:
- variable
- built-in function
- subfunction
- private function
- MEX-file (compiled m-file)
- P-file (pseudocode created from m-file)
- M-file
try:
>>
sin = 'this is a test'
sin(3)
which sin
clear sin
which sin
sin(3)
P-code - for most calculations p-code doesn't speed things up
use p-code to
hide original m-file source code
(28)
2-D Plotting
Plotting commands:
- plot - make 2-D plots
- grid on/off - turn grid on and off
- hold on/off -holds the current plots
- title - adds a title to the plot
- xlabel - adds an x axis label
- ylabel - adds a y axis label
- legend - add a legend to the plot
- text - add text to a specified position on the plot
- gtext - interactively place text on the plot
- ginput - pick off coordinates from a plot
Try:
>> plot2D
echo on
x = 0:0.1:2*pi;
y=sin(x);
plot(x,y)
grid on
hold on
plot(x,exp(-x),'r:*');
axis ([ 0 2*pi 0 1])
title('2-D Plots');
xlabel('Time');
ylabel('Sin(t)');
text(pi/3,sin(pi/3),'<--sin(\pi/3)')
legend('Sine Wave','Decaying
Exponential');
echo off
(29)
Graphics Objects
Hierarchy of Matlab
Graphics Objects (used to display matlab graphics)
Commands for Working With Graphics Objects:
gca - return the handle of the current axes
gcf - return the handle of the current figure
gco - return the handle of the current object
get - query the values of an object's properties
set - set the values of an object's properties
findall - find all graphics objects
findobj - find the handles of objects having specified property
values
Try :
x=0:.1:10;
y=sin(x);
plot(x,y);
axes_props=get(gca);
set(gca,'TickLength',[.04 .04]);
a=get(gca,'YLim');
set (gca,'YLim', [-1 2]);
b=findobj(gcf,'Color','blue');
get(b(1))
(30)
Matlab Debugging Tips
- Add keyboard command to
m-file
- example variables from the workspace
- hit enter key to continue execution
- Remove selected semicolons from line of m-file
- Use the disp command
- disp('in the else if section')
- Use the sprintf command
along with disp
- str1=sprintf('in for loop i =
%d,temp(i)=%g\n',i,temp(i));
- disp(str1);
try:
>>
[tsum,avg]=stats_error(rand(1,50))
(31)
Visual Debugging
Matlab Editor/Debugger
- set explicit breakpoints
- set automatic breakpoints (stop on error, NaN or Inf)
- step through execution of an M-file
- view the contents of the workspace
try:
>> collatzplot(6)
function collatzplot(m)
% Plot length of sequence for
Collatz problem
% Prepare figure
clf
set(gcf,'DoubleBuffer','on')
set(gca,'XScale','linear')
%
% Determine and plot sequence and
sequence length
for N = 1:m
plot_seq =
collatz(N);
seq_length(N)
= length(plot_seq);
line(N,plot_seq,'Marker','.','MarkerSize',9,'Color','blue')
drawnow
end
function
sequence=collatz(n)
% Collatz problem. Generate a
sequence of integers resolving to 1
% For any positive integer, n:
% Divide n by 2 if n
is even
% Multiply n by 3 and
add 1 if n is odd
% Repeat for the
result
% Continue until the
result is 1%
sequence = n;
next_value = n;
while next_value > 1
if
rem(next_value,2)==0
next_value = next_value/2;
else
next_value = 3*next_value+1;
end
sequence =
[sequence, next_value];
end
(32)
Profiling M-files
Matlab Profiler
- Allows you to evaluate how much computation time each line of an
M-file uses
- Steps to profile
- Turn profiler on
- Call M-file
- Report Results
- Turn profiler off
command :
profile keyword
where keywords are:
- func_name: start profiling for the specified function
name
- on,off,done,reset to control profiler's operation
- viewer to display a summary report for the M-file being
profiled
try:
>> profile on
>> bench
>> profile viewer
>> profile off
(33)
Matlab Resources at Dartmouth
Dartmouth Matlab Licenses
- 125 floating licenses
- Toolboxes
- Statistics
- Signal Processing
- Image Processing
- Control
- Partial Differential Equations
- Curve Fitting
- Neural Networks
- Optimization
- Compiler
- Symbolic
- Platforms
- Windows
- Mac OS X
- UNIX (including Linux)
Dartmouth Matlab Users Mailing List
matlab-users@listserv.dartmouth.edu
Support:
- email support@mathworks.com (include license #
207107)
- contact Susan Schwarz (Susan.A.Schwarz@dartmouth.edu)
- www.mathworks.com/support
Matlab Tutorials on the Web:
Professor Hany Farid's Matlab tutorial
http://www.cs.dartmouth.edu/farid/tutorials/matlab.intro.html
Topics Overview: Course Handout
(last update Wednesday, 17-Oct-2007 12:53:58 EDT) ©Dartmouth College
http://www.dartmouth.edu/~rc/classes/matlab_prog