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
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
2.The Matlab Path
3.Matlab Data Types
4.Entering Matrices
5.Multidimensional Arrays
6.String Arrays
7.Matlab Cell Arrays
8.Matlab Structures
9.Boolean Operators
10.Logic Control Constructs
11.For and While Loops
12.Vectorization
13.Preallocation
14.Loading and Saving Data
15.Importing Data into Matlab
16.Functions
17.Matlab Workspaces
18.Function_Details
19.Function Inputs and Outputs
20.Exercise - Write a function
21.Answer To Exercise
22.Types of Matlab Functions
23.Matlab Anonymous Function Example
24.Matlab Subfunction and Function Handle Example
25.Nested Matlab function example
26.Tips on Using Global Variables
27.Matlab Calling Priority
28.2D Plotting
29.Graphics Objects
30.Tips for Debugging Your Matlab Programs
31.Visual Debugging
32.Profiling M-files
33.Matlab Resources

(1)

  Types of Program Files


      M-files : ASCII text files that contain sequences of matlab commands (.m file extension)
      

2 kinds of M-files:
Can be created in matlab editor or an editor of your choice

                                                                          





(2)

The Matlab Path  


try:
      path
    pathtool



(3)

Matlab Data Types


diagram of matlab data types

Default Numeric Data Type - double

(4)

Defining Numerical Matrices                   



Square Brackets
Use of Colons
Parentheses
   
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)

Multidimensional Arrays    

  
Matlab Multidimensional Arrays:

Examples:

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



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



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)


picture of cell array B










(8)

Structures




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



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                 



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


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



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

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


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


        Differences between Script and Function M-Files




(17)

Workspaces In Matlab






(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
Optional
Command Line Syntax
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
>>
[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




(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



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:


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:

Try:

>> plot2D

plot of blue sine wave
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)

Diagram of Graphics Object Hierarchy 

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



try:
>>
[tsum,avg]=stats_error(rand(1,50))




(31)

Visual Debugging



Matlab Editor/Debugger

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

command :
profile keyword

where keywords are:
try:
>> profile on
>> bench
>> profile viewer
>> profile off






(33)

Matlab Resources at Dartmouth


Dartmouth Matlab Licenses
   Dartmouth Matlab Users Mailing List
    matlab-users@listserv.dartmouth.edu

   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