Overview
Course Handout: (last update 27 January 2014)
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 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 and Functions
- Working with data
- 2D Plotting
Click here to download the examples
used in the class.
Table of Contents
(1)
Resources for Learning Matlab
(2)
MATLAB Desktop
- MATLAB Command Window
- Workspace Browser
- Command History Window
- Current Folder Window
- Editor/Debugger
- Help
- Array Editor
- Setting the path
Getting Help in MATLAB
- Help Window
- 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
- function browser
- search for matlab functions
- brief description
- shows inputs and outputs
(4)
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
(5)
Working With Matrices
- MATLAB stands for MATrix LABoratory
- Basic Data Element is a Matrix
- Matrix does not require dimensioning
- Matrix can have numbers (arrays) or characters (string arrays)
- All numbers stored in double precision by default
- Matlab can perform operations on matrices
(6)
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
(7)
Matrix Operations
- Scalar (add, subt,mult,divide)
- 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
(8)
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
(9)
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
(10)
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
|
|
(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)
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)
(15)
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
(16)
Import, Analyze and Plot Data
- Import gas price data
- Examine data values
- Plot data
- Analyze data
- Write a matlab program
- Publish program and its results
See gasprices.m
(17)
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
Subplots
subplot - display multiple
plots in the same window
subplot (nrows,ncols,plot_number)
Try:
>> subplotex
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);
(19)
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
(20)
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
(21)
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
Matlab Resources
Dartmouth Matlab Site License
- Unlimited stand-alone licenses
- 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
Dartmouth Matlab Download
http://caligari.dartmouth.edu/downloads/matlab
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
Overview: Course Handout
[an error occurred while processing this directive]
(last update 27 January 2014) ©Dartmouth College
http://www.dartmouth.edu/~rc/classes/intro_matlab