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
Click here to download the examples used in the class.

Slides for Intro to Matlab class are here.

                                                                                       








Table of Contents

1.Matlab Data Types
2.Matrix Operations
3.Matrix and Array Operators
4.String Arrays
5.Matlab Cell Arrays
6.Matlab Structures
7.The Matlab Path
8.Types of Program Files
9.Array Subscripting and Indexing
10.Logical Indexing
11.Boolean Operators
12.Logic Control Constructs
13.For and While Loops
14.Vectorization
15.Functions
16.Function_Details
17.Write A Function
18.Types of Matlab Functions
19.Matlab Workspaces
20.Tips on Using Global Variables
21.Matlab Calling Priority
22.Tips for Debugging Your Matlab Programs
23.Profiling M-files
24.Matlab Resources

(1)

Matlab Data Types


diagram of matlab data types

Default Numeric Data Type - double

(2)

 Matrix Operations


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



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



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)


picture of cell array B










(6)

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









(7)

The Matlab Path  


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

Example of Matrix Indexing

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:













(10)

Logical Indexing



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



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                 



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


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



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


        Differences between Script and Function M-Files




(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
Optional
Command Line Syntax
Try:
>> a=rand(5);
>> b=mymean(a)









(17)

Function to Determine the Number of Days in each Month


days_in_month.m

(18)

Types of Matlab Functions



try:
>> f=@(x)(sin(x)+cos(x));
f(2)

(19)

Workspaces In Matlab






(20)

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


(21)

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





(22)

  Matlab Debugging Tips

Add Print Commands

Matlab Editor/Debugger



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




(23)

Profiling M-files

Matlab Profiler

command :
profile keyword

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






(24)

Matlab Resources


Dartmouth Matlab Site License
   Dartmouth Matlab Download
   http://caligari.dartmouth.edu/downloads/matlab

   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