# Topics Overview

### Course Handout: (last update 11 February 2014)

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, string arrays, cell arrays, structures)
• Array Operations
• Boolean Operations
• Logical control Constructs
• Matlab Functions
• Matlab Workspaces
• Debugging
• Profiling

Slides for Intro to Matlab class are here.

(1)

## Matlab Data Types

Default Numeric Data Type - double

(2)

### Matrix Operations

• scalar's size is increased to match the matrix
• Matrix Concatenation
• Binary (add,subt,mult,divide, raise to power, transpose)
Try:
>> a=[2 4; 6 8] +10
a  =
12     14
16      18
>>  b = [2 4; 6 8] * 3
b =
6      12
18      24

Try:
>> c = [1 2; 3 4]
c =
1      2
3      4

>> cc = [ c c]
cc =
1      2       1        2
3      4       3        4

Try:
>>  a=[2 4; 6 8];
>>  b = [ 1 3; 5 7];
>> c= a+b
c   =
3      7
11     15
>> d = a*b
d    =
22     34
46     74

>> e = a.*b
e   =
2     12
30     56

>> f = a^2
f       =
28     40
60     80

>> g= a.^2
g        =
4     16
36     64

(3)

### Matrix and Array Operators (listed in order of precedence)

 Matrix Operators Array Operators ( ) parentheses '   complex conjugate transpose .' array transpose ^  raise to a  power .^ array power * multiplication .* multiplication / division ./ array division \ left division + addition - subtraction

(4)

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

(5)

## 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]

A{1}
A{2}

B{1,1}=1:8;
B{1,2}=strvcat('Monday','Tuesday','Wednesday','Thursday');
B{2,2}=A;
B{1,1}
cellplot(B)

(6)

## 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(2).name = 'John';

or

students(1).name

(7)

## 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)
try:
path
pathtool

(8)

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

(9)

### More Array Subscripting and Indexing in MATLAB

Array indices must be integers and can refer to:

•  A single element
• A continuous range of elements
• Use colon  operator min:step:max
• A randomly assorted list of elements

Try:
>> first_mat
>> A([ 1 7 2; 3 6 2])

ans =  4.000      1.200      8.000
7.2          10.0000    8.000

>> A(1:5,5)
>> A(:,5)
>> A(21:25)
>> A(1:end,end)
>> A(:,end)
>>A(21:end)'
>> A(4:5,2:3)
>>A([9 14; 10 15])

>>B= find(A>5)
>> C=size(A)

Useful Subscripting commands:
• find - returns index/subscript values for elements that satify a given condition
• ind2sub - converts element-wise index values to row-column subscript values
• sub2ind - converts row-column subscript values to element-wise index values
• size   - returns the numbers of rows and columns in the matrix

(10)

### Logical Indexing

• Uses a logical array for the array indices
• Every true or 1 value is a positional index

Try:

A = [1 2 3; 4 5 6; 7 8 9]
A =
1     2     3
4     5     6
7     8     9

B = logical([0 1 0; 1 0 1; 0 0 1]);
B =
0     1     0
1     0     1
0     0     1

A(B)
ans =
4
2
6
9

C=A>5
C =
0     0     0
0     0     1
1     1     1

A(C)
ans =
7
8
6
9

(11)

### 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==6;
>> a>0
>> a~=5
>> b= [ -5 8 Inf 50 NaN 0]
>>  b< 3
>> isfinite(b)
>> all(b)
>> isnan(b)

>> bool_ops

(12)

## Logic Control Constructs

• Logic Control
• if/elseif/else
• switch/case/otherwise
• Iterative Loops
• for
• while

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

(13)

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

(14)

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

(15)

## Functions

• Core MATLAB (built-in) functions
•  sin,abs,exp, ...
• MATLAB-supplied M-file functions
• mean,std,erf, ...
• User-created M-file functions
• functions you create
Differences between Script and Function M-Files
• Structural syntax
• Functions workspace, inputs and outputs

(16)

## 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
• 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)

(17)

## Function to Determine the Number of Days in each Month

• input must be the name of a month
• use a switch statement
• return the number of the days in the month
• return an error message when
• the input is not text
• the input is not the name of a month
• change the input text to lower case
days_in_month.m

(18)

## 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
try:
>> f=@(x)(sin(x)+cos(x));
f(2)

(19)

## 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
• persistent -persistent variables keep their value from one function call to another
• global - initialize global variables in source workspace first

(20)

## 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.
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.
global TICTOC
if nargout < 1
elapsed_time = etime(clock, TICTOC)
else
t = etime(clock, TICTOC);
end

(21)

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

(22)

## 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);

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:
>>
[tsum,avg]=stats_error(rand(1,50))

(23)

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

(24)

### Matlab Resources

• Toolboxes
•  Bioinformatics
• Compiler
• Control systems
• Curve fiitting
• Data acquisition
• Image Processing
• Instrument Control
• Optimization
• Parallel Computing
• Signal Processing
• Parallel
• SimMechanics
• SimScape
• Stateflow
• Statistics
• Symbolic math
• Platforms
• Windows
• Mac OS X
• Linux

Support:
•    email support@mathworks.com (include license # 903105, #903104)
•    contact Susan Schwarz (Susan.A.Schwarz@dartmouth.edu)
•   www.mathworks.com/support
Matlab Tutorial Videos on the Web:

Mathworks Intro to Matlab Video:
http://www.mathworks.com/company/events/webinars/wbnr31351.html?id=31351&p1=961663781&p2=961663799

List of Mathworks Tutorial Webinars:
http://www.mathworks.com/company/events/webinars/index.html

Topics Overview: Course Handout
[an error occurred while processing this directive] (last update   11 February 2014)  ©Dartmouth College     http://www.dartmouth.edu/~rc/classes/matlab_prog