Overview

Course Handout: (last update Tuesday, 29-Sep-2009 10:57:29 EDT)


These notes may be found at http://www.dartmouth.edu/~rc/classes/intro_matlab. The online version has many links to additional information and may be more up to date than the printed notes

Introduction to Matlab


Covered in this class:
Click here to download the examples used in the class.





Table of Contents

1.MATLAB Desktop
2.MATLAB Help
3.Command Line Calculations
4.Working With Matrices
5.Entering Matrices
6.Matrix Operations
7.Review of Matrix Multiplication
8.Array Multiplication
9.Matrices and Linear Algebra
10.Solving Simultaneous Equations
11.Array Operations
12.Matrix Indexing
13.Array Subscripting and Indexing
14.Multidimensional Arrays
15.String Arrays
16.Boolean Operators
17.Logic Control Constructs
18.For and While Loops
19.Loading and Saving Data
20.Script M-Files
21.Functions
22.Function_Details
23.Exercise1
24.Formatting Matlab Programs Using Cells
25.2_D Plotting Overview
26.2D Plotting
27.Matlab Subplots
28.Alternative Scales for Axes
29.Specialized Plotting Routines
30.3-D Surface Plotting
31.Printing and Saving Files
32.Editing Figures
33.Matlab Resources

(1)

MATLAB Desktop






(2)

Getting Help in MATLAB





(3)

Calculations at the Command Line

Try:
>> -5/(3.45+2.75)^2
ans =
-0.1301
>> (2+6i)*(2-6i)
ans =
40
>> sin(pi/4)
ans =
0.7071
>> exp(acos(0.3))
ans=3.547
>> a= factorial(12)
>> b= a* cos(.76);
>> b

Useful keys to remember:

;                       Suppress the output of results to the screen
up-arrow         scroll through previously typed commands
???up-arrow     scroll through commands beginning with ??? (command completion)
Esc                  Clear command line
Ctrl+C            Quit current operation and return control to the command line











(4)

 Working With Matrices






(5)

Entering 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













(6)

 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





















(7)

A Review of Matrix Multiplication


Rules of Matrix Multiplication

Matrix multiplication example

Try:
>> a  = [  1 2 3; 4 5 6]
a =
        1      2      3
        4      5      6
>>  b= ones (3,3)
b =
         1      1      1
         1      1      1
         1      1      1
>>  c= a*b
c  =
          6       6       6
         15      15      15






(8)

Array Multiplication (.*)


Rules of Array Multiplication

Example of Array multiplication

Try:
>> a = [ 1 2 3 ; 4 5 6]
a =
      1   2    3
      4   5    6
>> b=[1:3; 1:3]
b =
       1    2    3
       1    2    3
>> c = a.*b
 c =
       1      4     9
       4     10    18






(9)

Matrices and Linear Algebra (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





(10)

Solving Simultaneous Equations



Use backslash operator (\) to solve simultaneous equations

Solve for x1,x2,x3

-x1 + x2  + 2x3 = 2
3x1 - x2  + x3  = 6
-x1 + 3x2 + 4x3 = 4

Ax = b

Try:
a = [-1 1 2; 3 -1 1; -1 3 4];
b = [2;6;4];
x = a\b
x =
     1.000  
    -1.000
     2.000

Note:
Given: [a] = m by n  [x] = n x1  [b] = m by 1
For overdetermined systems (m>n):
For under determined systems (m<n)







(11)

Array Operations


Matlab uses matrix calculations
You do not have to use loops to perform matrix calculations

Example:  if you have 10000 samples of a,b  and c = a*b

Most efficient matrix command:
>> c= a*b;

Less efficient to use a loop
>> for i=1:10000
            c(i)= a(i)*b(i);


Try:
>> array_examp



(12)

Indexing into a Matrix (Array) in MATLAB


Two different ways of indexing:
Example of a matrix

Try:
>> first_mat
>> A(2,4)
ans =
          4
>>A(17)
ans  =
           4



(13)

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:













(14)

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]

(15)

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)











(16)

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


 


(17)

Logic Control Constructs                 



try:
x=34;
y=26;

if x>y
    z=1
elseif x==y
    z=0
else
   z=-1
end



(18)

For and While Loops



try:
a=100;
for i=1:a
    for j=1:2: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








(19)

Load and Save Functions



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






(20)

MATLAB Script M-Files



Useful commands in script file programming





(21)

Functions


        Differences between Script and Function M-Files




(22)

Structure of a Function M-File



Example of a function:

function y = mymean(x)
% mymean Average or mean value.
% For vectors, mymean(x) returns the
%mean value. For matrices, mymean(x)
% is a row vector containing the mean
% value of each column.
[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)









(23)

Exercise 1  - Analyze weather data


Hints:
help sort
[b,i]= sort(a)

Try:
>> index_mat








(24)

  Formatting Your Matlab Program With Cells




example of a matlab programs with cells

Open the m-file sample_cells.m in the matlab editor and select Publish to Html from the File Menu







(25)

2-D Plotting Overview


Specify x and y data
Specify title, axes labels, legends
Specify color, line style and marker symbol
Use either figure menus or commands


Plot a single data set:
plot(xdata,ydata,'color_linestyle_marker')

Plot two data sets:
plot(x1,y1,'b*-',x2,y2,'r+:')

Plot command parameters

Try:
>> help plot
>> x= -5:5;
y= x.^2;
plot(x,y,'bs:');









(26)

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









(27)

 Subplots



subplot - display multiple plots in the same window
subplot (nrows,ncols,plot_number)


Try:

 x=0:.1:2*pi;
subplot(2,2,1);
plot(x,sin(x));
subplot(2,2,2);
plot(x,cos(x));
subplot(2,2,3)
plot(x,exp(-x));
subplot(2,2,4);
plot(peaks);

picture of 4 plots made using subplot command










(28)

Alternative Scale for Axes




try:
>> other_axes

Pick of Plots With Laternative Axes











(29)

Specialized Plotting Routines



Picture of Matlab Special Plots 

try: spec_plots















(30)

3-D Surface Plotting



Examples of 3D surface plots

Try:
surf_3d



















(31)

Saving and Printing Figures


try:
print -dtiff test
print (gcf,'-deps','epstest');
print ('-f1','-djpeg','jpegtest');





















(32)

Editing Figures Exercise

Try:
>> plot2D

Interactively edit the plot as follows:
Picture of Edited 2D plot
















(33)

Matlab Resources


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









Overview: Course Handout
(last update   Tuesday, 29-Sep-2009 10:57:29 EDT)  ©Dartmouth College     http://www.dartmouth.edu/~rc/classes/intro_matlab