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
- General purpose program for technical computing
- Runs on Windows, Mac OS X and UNIX (including Linux)
- Special toolboxes in many areas
- Used in many disciplines
Covered in this class:
- Calculations at the Command Line
- Creating Variables
- Matrix/Vector Calculations
- Indexing into a matrix/vector
- Getting Help
- Calling A Function
- Creating and Using Script Files
- Working with data
- Working With Strings
- 2D Plotting
Click here to download the examples
used in the class.
Table of Contents
(1)
MATLAB Desktop
- MATLAB Command Window
- Workspace Browser
- Command History Window
- Current Directory Window
- Editor/Debugger
- Help
- Array Editor
- Setting the path
(2)
Getting Help in MATLAB
- Help Window
- Contents
- Index
- Search
- Demos
- help command
- in command window
- provides information about a specific matlab function
- shows input and out arguments
- doc command
- in help browser window
- provides information about a specfic matlab function
- shows input and output arguments
- includes examples of using the function
(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
- MATLAB stands for MATrix LABoratory
- Basic Data Element is a Matrix
- Matrix doesn't require dimensioning
- Matrix can have numbers (arrays) or characters (string arrays)
- All numbers stored in double precision
- Matlab can perform operations on matrices
(5)
Entering 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
(6)
Matrix Operations
- Scalar (add, subt,mult,divide)
- scalar's size is increased to match the matrix
- 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
(7)
A Review of Matrix Multiplication
Rules of Matrix Multiplication
- Inner dimensions must be the same
- Dimension of resulting matrix are outer most dimensions of two
multiplied matrices
- Resulting elements are the dot product of the rows of first
matrix with the columns of the second
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
- Matrices must have the same dimensions
- Dimensions of the resulting matrix are the same as the two
multiplied matrices
- Resulting elements are the product of corresponding elements in
the multipied matrices
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):
- left division uses least squares
regression "curve fit" of data
- you receive warning if the solution is
not unique (dependent columns)
For under determined systems (m<n)
- Left division uses QR factorization with
column pivoting
- Solution is not unique
(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:
- Use the row column format (row,column)
- the indicies start from the top left corner with index of 1
- Use the absolute index
- indexed in column major order
- absolute indices go from top to bottom and left to right
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:
- 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
(14)
Multidimensional Arrays
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]
(15)
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)
(16)
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
(17)
Logic Control Constructs
- Logic Control
- Iterative Loops
try:
x=34;
y=26;
if x>y
z=1
elseif x==y
z=0
else
z=-1
end
(18)
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: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
- 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
(20)
MATLAB Script M-Files
- Set of MATLAB command in an ASCII text file
- does not have inputs and outputs
- have a .m extension
- called by typing the name (without the .m extension)
- startup.m script MATLAB executes when it starts up
Useful commands in script file programming
- pause
- suspend execution - press any key to continue
- keyboard
- pause and return control to the command line
- useful for debugging
- can examine or change variables
- type return to continue
- input
- prompt user for input
- r= input('Enter the number of time steps.')
(21)
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
(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
- 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
- nargin - number of function input arguments
- nargout - number of function output arguments
Command Line Syntax
- matlab searches the path for an m-file with the specified
function name
Try:
>> a=rand(5);
>> b=mymean(a)
(23)
Exercise 1 - Analyze weather
data
- Load weather data
- >> load weather
- data consists of
- time vector
- w_data matrix contains 3 columns temperatures, pressure and
humidity
- Index into w_data to get the column of temperature data ( first
column)
- Find the maximum temperature
- Sort temperature from low to high
- Sort time so the result matches the sorted temperature indicies
- Find the time that the maximum temperature occurred
Hints:
help sort
[b,i]= sort(a)
Try:
>> index_mat
(24)
Formatting Your Matlab Program With Cells
- Separate your programs in sections (cells)
- Execute one cell at a time
- Publish and format program in html and Microsoft Word (Windows)
- Use %% to
indicate the start of a new cell
- Turn cell mode on and off from matlab editor
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+:')
Try:
>> help plot
>> x= -5:5;
y= x.^2;
plot(x,y,'bs:');
(26)
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
(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);
(28)
Alternative Scale for Axes
- plot - makes a plot of vectors or columns of matrices
- loglog - creates a plot using log (base 10) scales for both axes
- semilogx - creates a plot using a log scale for the x-axis and
linear scale for y
- semilogy - creates a plot using a log scale for the y-axis and
linear scale for x
- plotyy - creates a plot of 2 sets of data with separate vertical
scales
try:
>> other_axes
(29)
Specialized Plotting Routines
- bar - bar graph
- bar3h - horizontal 3D bar graph
- hist- histogram
- area - filled area plot
- pie3 - 3D pie chart
- rose -angle histogram plot
try: spec_plots
(30)
3-D Surface Plotting
- contour - 2D contour lines
- contourf - 2D filled contour lines
- contour3 - 3D contour lines
- plot3 - 3D lines of columns of data
- mesh - 3D wire-frame view of the surface
- surf - 3D perspective plot of the surface
- waterfall - 3D lines of rows of data with a reference
planer
Try:
surf_3d
(31)
Saving and Printing Figures
- Use options from File Menu in the Figure Window
- Print or save matlab command line
- Supports many formats postscript, tiff, jepg, eps, etc.
- print -device -option filename
- print (gcf,'-dpsc',filename) (used in batch files)
- Create an m-file from a figure
- Property Editor and Inspector Available in figure Window
try:
print -dtiff test
print (gcf,'-deps','epstest');
print ('-f1','-djpeg','jpegtest');
(32)
Editing Figures Exercise
Try:
>> plot2D
Interactively edit the plot as follows:
- change the y axis to go from -1 to 1
- change the decaying exponential line to use a square instead of *
- change the sine wave to be a green line instead of blue
- add a title of 'Sample 2D plot after editing'
- change x tics to be at 0,pi/2,pi, 3pi/2, 2pi
(33)
Matlab Resources
Dartmouth Matlab Licenses
- 125 floating licenses
- Toolboxes
- Statistics
- Signal Processing
- Image Processing
- Control
- Partial Differential Equations
- Curve Fitting
- Neural Networks
- Optimization
- Compiler
- Symbolic
- Distributed Computing
- Platforms
- Windows
- Mac OS X
- Linux and Solaris
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
Overview: Course Handout
(last update Tuesday, 29-Sep-2009 10:57:29 EDT) ©Dartmouth College
http://www.dartmouth.edu/~rc/classes/intro_matlab