Transcript
5/25/2018 Mit Matlab Course
1/205
EE 475 575 Digital Signal Processing, Spring 2010 (Dr. Mousavinezhad)
These MATLAB tutorials are from MITs Open Courseware Site:
http://ocw.mit.edu
5/25/2018 Mit Matlab Course
2/205
MIT OpenCourseWare
http://ocw.mit.edu
6.094 Introduction to MATLAB
January (IAP) 2009
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
http://ocw.mit.edu/http://ocw.mit.edu/termshttp://ocw.mit.edu/termshttp://ocw.mit.edu/termshttp://ocw.mit.edu/5/25/2018 Mit Matlab Course
3/205
6.094Introduction to Programming in MATLAB
Sourav DeyDanilo epanovi
Ankit PatelPatrick Ho
IAP 2009
Lecture 1: Variables, Operations, andPlotting
5/25/2018 Mit Matlab Course
4/205
Course Layout
Lectures (7pm-9pm)1: Variables, Operations and Plotting2: Visualization & Programming3: Solving Equations, Fitting4: Advanced Methods
5/25/2018 Mit Matlab Course
5/205
Course Layout
Problem Sets / Office HoursOne per day, should take about 3 hours to do
Submit doc or pdf (include pertinent code)
Requirements for passing
Attend all lecturesComplete all problem sets (FAIL, Check or +)
PrerequisitesBasic familiarity with programmingBasic linear algebra, differential equations, and
probability
5/25/2018 Mit Matlab Course
6/205
Outline
(1) Getting Started
(2) Making Variables
(3) Manipulating Variables
(4) Basic Plotting
5/25/2018 Mit Matlab Course
7/205
Getting Started
To get MATLAB Student Version for yourself https://msca.mit.edu/cgi-bin/matlab
Use VPN client to enable off-campus accessNote: MIT certificates are required
Open up MATLAB for Windows
Through the START Menu
On Athena
add matlabmatlab &
5/25/2018 Mit Matlab Course
8/205
Command Window
Current directory
Workspace
Command History
Courtesy of The MathWorks, Inc. Used with permission.
5/25/2018 Mit Matlab Course
9/205
Customization
File PreferencesAllows you personalize your MATLAB experience
Courtesy of The MathWorks, Inc. Used with permission.
5/25/2018 Mit Matlab Course
10/205
MATLAB Basics
MATLAB can be thought of as a super-powerfulgraphing calculator
Remember the TI-83 from calculus?
With many more buttons (built-in functions)
In addition it is a programming language MATLAB is an interpreted language, like
Scheme Commands executed line by line
5/25/2018 Mit Matlab Course
11/205
Conversing with MATLAB
who
MATLAB replies with the variables in your workspace
what
MATLAB replies with the current directory andMATLAB files in the directory
why
help
The most important function for learning MATLAB onyour own
More on help later
5/25/2018 Mit Matlab Course
12/205
Outline
(1) Getting Started
(2) Making Variables
(3) Manipulating Variables
(4) Basic Plotting
5/25/2018 Mit Matlab Course
13/205
Variable Types
MATLAB is a weakly typed languageNo need to initialize variables!
MATLAB supports various types, the most often used are 3.84
64-bit double (default) a
16-bit char
Most variables youll deal with will be arrays or matrices ofdoubles or chars
Other types are also supported: complex, symbolic, 16-bitand 8 bit integers, etc.
5/25/2018 Mit Matlab Course
14/205
Naming variables
To create a variable, simply assign a value to a name: var1=3.14
myString=hello world
Variable names first character must be a LETTER
after that, any combination of letters, numbers and _CASE SENSITIVE! (var1 is different fromVar1)
Built-in variablesi and j can be used to indicate complex numberspi has the value 3.1415926
ans stores the last unassigned value (like on a calculator)
Inf and -Inf are positive and negative infinity
NaN represents Not a Number
5/25/2018 Mit Matlab Course
15/205
Hello World
Here are several flavors of Hello World to introduce MATLAB
MATLAB will display strings automatically Hello 6.094
To remove ans =, use disp() disp('Hello 6.094')
sprintf() allows you to mix strings with variables
class=6.094; disp(sprintf('Hello %g', class))
The format is C-syntax
5/25/2018 Mit Matlab Course
16/205
Scalars
A variable can be given a value explicitly a = 10
shows up in workspace!
Or as a function of explicit values and existing variables c = 1.3*45-2*a
To suppress output, end the line with a semicolon
cooldude = 13/3;
5/25/2018 Mit Matlab Course
17/205
Arrays
Like other programming languages, arrays are animportant part of MATLAB
Two types of arrays
(1) matrix of numbers (either double or complex)
(2) cell array of objects (more advanced data structure)
MATLAB makes vectors easy!Thats its power!
5/25/2018 Mit Matlab Course
18/205
Row Vectors
Row vector: comma or space separated values betweenbrackets row = [1 2 5.4 -6.6];
row = [1, 2, 5.4, -6.6];
Command window:
Workspace:
Courtesy of The MathWorks, Inc. Used with permission.
5/25/2018 Mit Matlab Course
19/205
Column Vectors
Column vector: semicolon separated values betweenbrackets column = [4;2;7;4];
Command window:
Workspace:
Courtesy of The MathWorks, Inc. Used with permission.
5/25/2018 Mit Matlab Course
20/205
Matrices
Make matrices like vectors
Element by element a= [1 2;3 4];
By concatenating vectors or matrices (dimension matters) a = [1 2];
b = [3 4];
c = [5;6];
d = [a;b];
e = [d c];
f = [[e e];[a b a]];
1 2
3 4a
=
5/25/2018 Mit Matlab Course
21/205
save/clear/load
Use save to save variables to a file save myfile a b
saves variables a and b to the file myfile.mat myfile.mat file in the current directory Default working directory is
\MATLAB\work
Create own folder and change working directory to it MyDocuments\6.094\day1
Use clear to remove variables from environment clear a b
look at workspace, the variables a and b are gone
Use load to load variable bindings into the environment load myfile look at workspace, the variables a and b are back
Can do the same for entire environment
save myenv; clear all; load myenv;
5/25/2018 Mit Matlab Course
22/205
Exercise: Variables
Do the following 5 things:Create the variable r as a row vector with values 1 4
7 10 13
Create the variable c as a column vector with values13 10 7 4 1Save these two variables to file varExclear the workspace load the two variables you just created
r=[1 4 7 10 13];
c=[13; 10; 7; 4; 1];
save varEx r c
clear r c
load varEx
5/25/2018 Mit Matlab Course
23/205
Outline
(1) Getting Started
(2) Making Variables
(3) Manipulating Variables
(4) Basic Plotting
5/25/2018 Mit Matlab Course
24/205
Basic Scalar Operations
Arithmetic operations (+,-,*,/) 7/45
(1+i)*(2+i)
1 / 0
0 / 0
Exponentiation (^) 4^2
(3+4*j)^2
Complicated expressions, use parentheses ((2+3)*3)^0.1
Multiplication is NOT implicit given parentheses 3(1+0.7) gives an error
To clear cluttered command window Clc
5/25/2018 Mit Matlab Course
25/205
Built-in Functions
MATLAB has an enormous library of built-in functions
Call using parentheses passing parameter to function sqrt(2)
log(2), log10(0.23)
cos(1.2), atan(-.8)
exp(2+4*i)
round(1.4), floor(3.3), ceil(4.23)
angle(i); abs(1+i);
5/25/2018 Mit Matlab Course
26/205
Help/Docs
To get info on how to use a function: help sin
Help contains related functions To get a nicer version of help with examples and easy-to-
read descriptions: doc sin
To search for a function by specifying keywords: doc + Search tab
lookfor hyperbolic
One-word description of what
you're looking for
5/25/2018 Mit Matlab Course
27/205
Exercise: Scalars
Verify that e^(i*x) = cos(x) + i*sin(x) for a few values of x.
x = pi/3;
a = exp(i*x)
b = cos(x)+ i*sin(x)
a-b
5/25/2018 Mit Matlab Course
28/205
size & length
You can tell the difference between a row and a columnvector by:
Looking in the workspace
Displaying the variable in the command windowUsing the size function
To get a vector's length, use the length function
5/25/2018 Mit Matlab Course
29/205
transpose
The transpose operators turns a column vector into a rowvector and vice versa a = [1 2 3 4]
transpose(a)
Can use dot-apostrophe as short-cut a.'
The apostrophe gives the Hermitian-transpose, i.e.transposes and conjugates all complex numbers
a = [1+j 2+3*j] a'
a.'
For vectors of real numbers .' and ' give same result
ddi i d S b i
5/25/2018 Mit Matlab Course
30/205
Addition and Subtraction
Addition and subtraction are element-wise; sizes mustmatch (unless one is a scalar):
The following would give an error c = row + column
Use the transpose to make sizes compatible
c = row + column c = row + column
Can sum up or multiply elements of vector s=sum(row);
p=prod(row);
[ ]
[ ]
[ ]
12 3 32 11
2 11 30 32
14 14 2 21
+
=
12 3 9
1 1 2
10 13 23
0 33 33
=
El t Wi F ti
5/25/2018 Mit Matlab Course
31/205
Element-Wise Functions
All the functions that work on scalars also work on vectors t = [1 2 3];
f = exp(t);
is the same as f = [exp(1) exp(2) exp(3)];
If in doubt, check a functions help file to see if it handlesvectors elementwise
Operators (* / ^) have two modes of operation element-wise standard
O t l t i
5/25/2018 Mit Matlab Course
32/205
Operators: element-wise
To do element-wise operations, use the dot. BOTHdimensions must match (unless one is scalar)! a=[1 2 3];b=[4;2;1];
a.*b, a./b, a.^b all errors a.*b, a./b, a.^(b) all valid
[ ]4
1 2 3 2
1
1 4 4
2 2 4
3 1 3
3 1 3 1 3 1
.* ERROR
.*
.*
=
=
=
1 1 1 1 2 3 1 2 3
2 2 2 1 2 3 2 4 6
3 3 3 1 2 3 3 6 9
3 3 3 3 3 3
.*
.*
=
=
2 2
2 2
1 2 1 22
3 4 3 4.^
Can be any dimension
=
O t t d d
5/25/2018 Mit Matlab Course
33/205
Operators: standard
Multiplication can be done in a standard way or element-wise Standard multiplication (*) is either a dot-product or an outer-
product
Remember from linear algebra: inner dimensions must MATCH!! Standard exponentiation (^) implicitly uses *
Can only be done on square matrices or scalars
Left and right division (/ \) is same as multiplying by inverse
Our recommendation: just multiply by inverse (more on thislater)
[ ]
4
1 2 3 2 11
1
1 3 3 1 1 1
*
*
=
=
1 1 1 1 2 3 3 6 9
2 2 2 1 2 3 6 12 18
3 3 3 1 2 3 9 18 27
3 3 3 3 3 3
*
*
=
=
1 2 1 2 1 22
3 4 3 4 3 4^ *
Must be square to do powers
=
E e cise Vecto Ope ations
5/25/2018 Mit Matlab Course
34/205
Exercise: Vector Operations
Find the inner product between [1 2 3] and [3 5 4] a=[1 2 3]*[3 5 4]
Multiply the same two vectors element-wiseb=[1 2 3].*[3 5 4]
Calculate the natural log of each element of the resultingvector c=log(b)
Automatic Initialization
5/25/2018 Mit Matlab Course
35/205
Automatic Initialization
Initialize a vector of ones, zeros, or random numbers o=ones(1,10)
row vector with 10 elements, all 1 z=zeros(23,1)
column vector with 23 elements, all 0 r=rand(1,45)
row vector with 45 elements (uniform [0,1]) n=nan(1,69)
row vector of NaNs (useful for representing uninitializedvariables)
The general function call is:var=zer os(M,N) ;
Number of rows Number of columns
Automatic Initialization
5/25/2018 Mit Matlab Course
36/205
Automatic Initialization
To initialize a linear vector of values use linspace a=linspace(0,10,5)
starts at 0, ends at 10 (inclusive), 5 values
Can also use colon operator (:)b=0:2:10
starts at 0, increments by 2, and ends at or before 10 increment can be decimal or negative
c=1:5
if increment isnt specified, default is 1
To initialize logarithmically spaced values use logspace similar to linspace
Exercise: Vector Functions
5/25/2018 Mit Matlab Course
37/205
Exercise: Vector Functions
Make a vector that has 10,000 samples off(x) = e^{-x}*cos(x), for x between 0 and 10.
x = linspace(0,10,10000);
f = exp(-x).*cos(x);
Vector Indexing
5/25/2018 Mit Matlab Course
38/205
Vector Indexing
MATLAB indexing starts with 1, not 0We will not respond to any emails where this is the
problem.
a(n) returns the nth element
The index argument can be a vector. In this case, eachelement is looked up individually, and returned as a vectorof the same size as the index vector. x=[12 13 5 8];
a=x(2:3); a=[13 5];
b=x(1:end-1); b=[12 13 5];
[ ]13 5 9 10
a(1) a(2) a(3) a(4)
Matrix Indexing
5/25/2018 Mit Matlab Course
39/205
Matrix Indexing
Matrices can be indexed in two ways using subscripts (row and column) using linear indices (as if matrix is a vector)
Matrix indexing: subscripts or linear indices
Picking submatricesA = rand(5) % shorthand for 5x5 matrix
A(1:3,1:2) % specify contiguous submatrix
A([1 5 3], [1 4]) % specify rows and columns
14 33
9 8
b(1)
b(2)
b(3)
b(4)
14 33
9 8
b(1,1)
b(2,1)
b(1,2)
b(2,2)
Advanced Indexing 1
5/25/2018 Mit Matlab Course
40/205
Advanced Indexing 1
The index argument can be a matrix. In this case, eachelement is looked up individually, and returned as a matrixof the same size as the index matrix.
a=[-1 10 3 -2];
b=a([1 2 4;3 4 2]);
To select rows or columns of a matrix, use the :
d=c(1,:); d=[12 5];
e=c(:,2); e=[5;13];
c(2,:)=[3 6]; %replaces second row of c
1 10 2
3 2 10b
=
12 5
2 13
c =
Advanced Indexing 2
5/25/2018 Mit Matlab Course
41/205
Advanced Indexing 2
MATLAB contains functions to help you find desired valueswithin a vector or matrix vec = [1 5 3 9 7]
To get the minimum value and its index: [minVal,minInd] = min(vec);
To get the maximum value and its index:
[maxVal,maxInd] = max(vec); To find any the indices of specific values or ranges
ind = find(vec == 9);
ind = find(vec > 2 & vec < 6);
find expressions can be very complex, more on this later
To convert between subscripts and indices, use ind2sub,and sub2ind. Look up help to see how to use them.
Exercise: Vector Indexing
5/25/2018 Mit Matlab Course
42/205
Exercise: Vector Indexing
Evaluate a sine wave at 1,000 points between 0 and 2*pi. Whats the value at
Index 55 Indices 100 through 110
Find the index of the minimum value, the maximum value, and
values between -0.001 and 0.001
x = linspace(0,2*pi,1000);
y=sin(x); y(55)
y(100:110)
[minVal,minInd]=min(y)
[maxVal,maxInd]=max(y)
inds=find(y>-0.001 & y
5/25/2018 Mit Matlab Course
43/205
BONUS Exercise: Matrices
Make a 3x100 matrix of zeros, and a vector x that has 100 valuesbetween 0 and 10mat=zeros(3,100);
x=linspace(0,10,100);
Replace the first row of the matrix with cos(x)mat(1,:)=cos(x);
Replace the second row of the matrix with log((x+2)^2)mat(2,:)=log((x+2).^2);
Replace the third row of the matrix with a random vector of thecorrect sizemat(3,:)=rand(1,100);
Use the sum function to compute row and column sums of mat(see help) rs = sum(mat,2);
cs = sum(mat); % default dimension is 1
Outline
5/25/2018 Mit Matlab Course
44/205
Outline
(1) Getting Started
(2) Making Variables
(3) Manipulating Variables
(4) Basic Plotting
Plotting Vectors
5/25/2018 Mit Matlab Course
45/205
Plotting Vectors
Example x=linspace(0,4*pi,10);
y=sin(x);
Plot values against their indexplot(y);
Usually we want to plot y versus xplot(x,y);
MATLAB makes visualizing datafun and easy!
What does plot do?
5/25/2018 Mit Matlab Course
46/205
What does plot do?
plot generates dots at each (x,y) pair and then connects the dotswith a line
To make plot of a function look smoother, evaluate at more points x=linspace(0,4*pi,1000);
plot(x,sin(x));
x and y vectors must be same size or else youll get an errorplot([1 2], [1 2 3])
error!!
10 x values:
0 2 4 6 8 10 12 14-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
0 2 4 6 8 10 12 14-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
1000 x values:
Plot Options
5/25/2018 Mit Matlab Course
47/205
Plot Options
Can change the line color, marker style, and line style byadding a string argumentplot(x,y,k.-);
Can plot without connecting the dots by omitting line style
argumentplot(x,y,.)
Look at help plot for a full list of colors, markers, andlinestyles
color marker line-style
Other Useful plot Commands
5/25/2018 Mit Matlab Course
48/205
p
Much more on this in Lecture 2, for now some simplecommands
To plot two lines on the same graph hold on; To plot on a new figure
figure;
plot(x,y);
Play with the figure GUI to learn more add axis labels add a title add a grid zoom in/zoom out
Exercise: Plotting
5/25/2018 Mit Matlab Course
49/205
g
Plot f(x) = e^x*cos(x) on the interval x = [0 10]. Use a redsolid line with a suitable number of points to get a goodresolution.
x=0:.01:10;
plot(x,exp(x).*cos(x),r);
End of Lecture 1
5/25/2018 Mit Matlab Course
50/205
(1) Getting Started
(2) Making Variables
(3) Manipulating Variables
(4) Basic Plotting
Hope that wasnt too much!!
MIT OpenCourseWare
http://ocw.mit.edu
http://ocw.mit.edu/http://ocw.mit.edu/5/25/2018 Mit Matlab Course
51/205
6.094 Introduction to MATLABJanuary (IAP) 2009
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
http://ocw.mit.edu/termshttp://ocw.mit.edu/termshttp://ocw.mit.edu/terms5/25/2018 Mit Matlab Course
52/205
6.094Introduction to Programming in MATLAB
Lecture 2: Visualization and Programming
Sourav DeyDanilo epanovi
Ankit PatelPatrick Ho
IAP 2009
Outline
5/25/2018 Mit Matlab Course
53/205
(1) Plotting Continued
(2) Scripts
(3) Functions
(4) Flow Control
Cartesian Plots
5/25/2018 Mit Matlab Course
54/205
We have already seen the plot functionx=-pi:pi/100:pi;
y=cos(4*x).*sin(10*x).*exp(-abs(x));
plot(x,y,'k-');
The same syntax applies for semilog and loglog plots
semilogx(x,y,'k');semilogy(y,'r.-');
loglog(x,y);
For example:x=0:100;
semilogy(x,exp(x),'k.-');0 10 20 30 40 50 60 70 80 90 100
100
1010
1020
1030
1040
1050
Playing with the Plot
5/25/2018 Mit Matlab Course
55/205
to select linesand delete orchange
propertiesto zoom in/out
to slide the plotaround
to see all plottools at once
Courtesy of The MathWorks, Inc. Used with permission.
Line and Marker Options
5/25/2018 Mit Matlab Course
56/205
Everything on a line can be customizedplot(x,y,'--rs','LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g',...
'MarkerSize',10)
See doc line for a full list ofproperties that can be specified
-4 -3 -2 -1 0 1 2 3 4-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
Labels
5/25/2018 Mit Matlab Course
57/205
Last time we saw how to add titles and labels using the GUI. Canalso do it command-line:title('Stress-Strain');
xlabel('Force (N)');
For multiple lines, add a legend entry for each linelegend('Steel','Aluminum','Tungsten');
Can specify font and size for the textylabel('Distance (m)','FontSize',14,...
'FontName','Helvetica');
use ... to break long commands across multiple lines
To put parameter values into labels, need to use num2str andconcatenate:str = [Strength of ' num2str(d) 'cm diameter rod'];
title(str)
Axis
5/25/2018 Mit Matlab Course
58/205
A grid makes it easier to read valuesgrid on
xlim sets only the x axis limitsxlim([-pi pi]);
ylim sets only the y axis limitsylim([-1 1]);
To specify both at once, use axis:axis([-pi pi -1 1]);
sets the x axis limits between -pi and pi and the y axis limitsbetween -1 and 1
Can specify tickmarksset(gca,'XTick', linspace(-pi,pi,3))
see doc axes for a list of properties you can set this way more on advanced figure customization in lecture 4
Axis Modes
5/25/2018 Mit Matlab Course
59/205
Built-in axis modes
axis square
makes the current axis look like a boxaxis tight
fits axes to dataaxis equalmakes x and y scales the same
axis xy
puts the origin in the bottom left corner (default)
axis ij
puts the origin in the top left corner (for viewing matrices)
Multiple Plots in one Figure
5/25/2018 Mit Matlab Course
60/205
Use the figure command to open a new figurefigure
or activate an open figurefigure(1)
To have multiple axes in one figuresubplot(2,3,1) or subplot(231)
makes a figure with 2 rows and three columns of axes, andactivates the first axis for plotting
each axis can have labels, a legend, and a titlesubplot(2,3,4:6)
activating a range of axes fuses them into one
To close existing figuresclose([1 3])
closes figures 1 and 3
close all closes all figures (useful in scripts/functions)
Copy/Paste Figures
5/25/2018 Mit Matlab Course
61/205
Figures can be pasted into other apps (word, ppt, etc) Edit copy options figure copy templateChange font sizes, line properties; presets for word and ppt
Edit copy figure to copy figure Paste into document of interest
Courtesy of The MathWorks, Inc. Used with permission.
Saving Figures
5/25/2018 Mit Matlab Course
62/205
Figures can be saved in many formats. The common onesare:
.fig preserves allinformation
.bmp uncompressedimage
.eps high-qualityscaleable format
.pdfcompressed
imageCourtesy of The MathWorks, Inc.
Used with permission.
Figures: Exercise
5/25/2018 Mit Matlab Course
63/205
Open a figure and plot a sine wave over two periods withdata points at 0, pi/8, 2pi/8 . Use black squares asmarkers and a dashed red line of thickness 2 as the line
figureplot(0:pi/4:4*pi,sin(0:pi/4:4*pi),'rs--',...
'LineWidth',2,'MarkerFaceColor','k');
Save the figure as a pdf
View with pdf viewer.
Visualizing matrices
5/25/2018 Mit Matlab Course
64/205
Any matrix can be visualized as an imagemat=reshape(1:10000,100,100);
imagesc(mat);
colorbar
imagesc automatically scales the values to span the entire
colormap
Can set limits for the color axis (analogous to xlim, ylim)caxis([3000 7000])
Colormaps
5/25/2018 Mit Matlab Course
65/205
You can change the colormap:imagesc(mat) default map isjet
colormap(gray)
colormap(cool)
colormap(hot(256))
See help hot for a list
Can define custom colormapmap=zeros(256,3);
map(:,2)=(0:255)/255;
colormap(map);
Images: Exercise
5/25/2018 Mit Matlab Course
66/205
Construct a Discrete Fourier Transform Matrix of size 128using dftmtx
Display the phase of this matrix as an image using a hot
colormap with 256 colors
dMat=dftmtx(128);
phase=angle(dMat);
imagesc(phase);
colormap(hot(256));
3D Line Plots
5/25/2018 Mit Matlab Course
67/205
-1
-0.5
0
0.5
1
-1
-0.5
0
0.5
1
-10
-5
0
5
10
We can plot in 3 dimensions just as easily as in 2time=0:0.001:4*pi;
x=sin(time);
y=cos(time);
z=time;
plot3(x,y,z,'k','LineWidth',2);
zlabel('Time');
Use tools on figure to rotate it Can set limits on all 3 axes
xlim, ylim, zlim
Surface Plots
5/25/2018 Mit Matlab Course
68/205
It is more common to visualize surfaces in 3D
Example:
surfputs vertices at specified points in space x,y,z, and
connects all the vertices to make a surface
The vertices can be denoted by matrices X,Y,Z
How can we make these matrices loop (DUMB) built-in function: meshgrid
( ) ( ) ( )
[ ] [ ]
f x, y sin x cos y
x , ; y ,
=
surf
5/25/2018 Mit Matlab Course
69/205
Make the x and y vectorsx=-pi:0.1:pi;
y=-pi:0.1:pi;
Use meshgrid to make matrices (this is the same as loop)[X,Y]=meshgrid(x,y);
To get function values,evaluate the matricesZ =sin(X).*cos(Y);
Plot the surfacesurf(X,Y,Z)
surf(x,y,Z);
surf Options
5/25/2018 Mit Matlab Course
70/205
See help surffor more options There are three types of surface shading
shading faceted
shading flat
shading interp
You can change colormaps
colormap(gray)
contour
5/25/2018 Mit Matlab Course
71/205
You can make surfaces two-dimensional by using contourcontour(X,Y,Z,'LineWidth',2)
takes same arguments as surf
color indicates height can modify linestyle properties can set colormap
hold on
mesh(X,Y,Z)
Exercise: 3-D Plots
5/25/2018 Mit Matlab Course
72/205
Plot exp(-.1(x^2+y^2))*sin(xy) for x,y in [2*pi,2*pi]with interpolated shading and a hot colormap:
x=-2*pi:0.1:2*pi;y=-2*pi:0.1:2*pi;
[X,Y]=meshgrid(x,y);
Z =exp(-.1*(X.^2+Y.^2)).*sin(X.*Y);
surf(X,Y,Z);
shading interp
colormap hot
Specialized Plotting Functions
5/25/2018 Mit Matlab Course
73/205
MATLAB has a lot of specialized plotting functions polar-to make polar plots
polar(0:0.01:2*pi,cos((0:0.01:2*pi)*2))
bar-to make bar graphsbar(1:10,rand(1,10)); quiver-to add velocity vectors to a plot
[X,Y]=meshgrid(1:10,1:10);
quiver(X,Y,rand(10),rand(10));
stairs-plot piecewise constant functionsstairs(1:10,rand(1,10));
fill-draws and fills a polygon with specified verticesfill([0 1 0.5],[0 0 1],'r'); see help on these functions for syntax doc specgraph for a complete list
Outline
5/25/2018 Mit Matlab Course
74/205
(1) Plotting Continued
(2) Scripts
(3) Functions(4) Flow Control
Scripts: Overview
5/25/2018 Mit Matlab Course
75/205
Scripts arewritten in the MATLAB editor saved as MATLAB files (.m extension)
evaluated line by line
To create an MATLAB file from command-lineedit myScript.m
or click
Courtesy of The MathWorks, Inc. Used with permission.
Scripts: the Editor
5/25/2018 Mit Matlab Course
76/205
* Means that it's not savedLine numbers
Debugging tools
Comments
MATLABfile path
Help file
Possible breakpointsCourtesy of The MathWorks, Inc. Used with permission.
Scripts: Good Practice
5/25/2018 Mit Matlab Course
77/205
Take advantage of "smart indent" option
Keep code clean
Use built-in functionsVectorize, vectorize, vectorizeWhen making large matrices, allocate space first
Use nan or zeros to make a matrix of the desired size
Keep constants at the top of the MATLAB file
COMMENT!Anything following a % is seen as a comment The first contiguous comment becomes the script's help fileComment thoroughly to avoid wasting time later
Hello World
5/25/2018 Mit Matlab Course
78/205
Here are several flavors of Hello World to introduce MATLAB
MATLAB will display strings automatically
Hello 6.094
To remove ans =, use disp()disp('Hello 6.094')
sprintf() allows you to mix strings with variablesclass=6.094;
disp(sprintf('Hello %g', class))
The format is C-syntax
Exercise: Scripts
5/25/2018 Mit Matlab Course
79/205
A student has taken three exams. The performance on theexams is random (uniform between 0 and 100)
The first exam is worth 20%, the second is worth 30%, and
the final is worth 50% of the grade Calculate the student's overall score Save script as practiceScript.m and run a few times
scores=rand(1,3)*100;
weights=[0.2 0.3 0.5];
overall=scores*weights
Outline
5/25/2018 Mit Matlab Course
80/205
(1) Plotting Continued
(2) Scripts
(3) Functions(4) Flow Control
User-defined Functions
5/25/2018 Mit Matlab Course
81/205
Functions look exactly like scripts, but for ONE difference Functions must have a function declaration
Help file
Function declarationInputsOutputs
Courtesy of The MathWorks, Inc. Used with permission.
User-defined Functions
5/25/2018 Mit Matlab Course
82/205
Some comments about the function declaration
No need for return: MATLAB returns the variables whosenames match those in the function declaration
Variable scope: Any variables created within the functionbut not returned disappear after the function stops running
Can have variable input arguments (see help varargin)
function [x, y, z] = funName(in1, in2)
Must have the reservedword: function
Function name shouldmatch MATLAB filenameIf more than one output,
must be in brackets
Inputs must be specified
Functions: Exercise
5/25/2018 Mit Matlab Course
83/205
Take the script we wrote to calculate the student's overallscore and make it into a function
The inputs should be the scores row vector the weight row vector, with the same length as scores
The output should beA scalar: the overall score
Assume the user knows the input constraints (no need to
check if the inputs are in the correct format\size)
Name the function overallScore.m
Functions: Exercise
5/25/2018 Mit Matlab Course
84/205
Courtesy of The MathWorks, Inc. Used with permission.
Functions
5/25/2018 Mit Matlab Course
85/205
We're familiar withzeros
size
length
sum
Look at the help file for size by typing
help size
The help file describes several ways to invoke the functionD = SIZE(X) [M,N] = SIZE(X) [M1,M2,M3,...,MN] = SIZE(X)M = SIZE(X,DIM)
Functions
5/25/2018 Mit Matlab Course
86/205
MATLAB functions are generally overloadedCan take a variable number of inputsCan return a variable number of outputs
What would the following commands return:a=zeros(2,4,8);
D=size(a)
[m,n]=size(a)
[x,y,z]=size(a)
m2=size(a,2)
Take advantage of overloaded methods to make your codecleaner!
Outline
5/25/2018 Mit Matlab Course
87/205
(1) Plotting Continued
(2) Scripts
(3) Functions(4) Flow Control
Relational Operators
tl
5/25/2018 Mit Matlab Course
88/205
MATLAB uses mostlystandard relational operators equal == not equal ~= greater than > less than < greater or equal >= less or equal
5/25/2018 Mit Matlab Course
89/205
Basic flow-control, common to all languages MATLAB syntax is somewhat unique
IFifcond
commands
end
ELSEifcond
commands1
elsecommands2
end
ELSEIFifcond1
commands1
elseifcond2commands2
else
commands3end
No need for parentheses: command blocks are between
reserved words
Conditional statement:
evaluates to true or false
for
5/25/2018 Mit Matlab Course
90/205
for loops: use for a definite number of iterations MATLAB syntax:
for n=1:100commands
end
The loop variable Is defined as a vector Is a scalar within the command block
Does not have to have consecutive values The command block
Anything between the for line and the end
Loop variable
Command block
while
h h l l k l f l
5/25/2018 Mit Matlab Course
91/205
The while is like a more general for loop:Don't need to know number of iterations
The command block will execute while the conditionalexpression is true
Beware of infinite loops!
WHILE
while cond
commandsend
Exercise: Control-Flow
W it f ti t l l t th f t i l f i t N i
5/25/2018 Mit Matlab Course
92/205
Write a function to calculate the factorial of an integer N using aloop (you can use a for or while loop). If the input is less than 0,return NaN. Test it using some values.
function a = factorial(N)
if N
5/25/2018 Mit Matlab Course
93/205
find is a very important functionReturns indices of nonzero valuesCan simplify code and help avoid loops
Basic syntax: index=find(cond)x=rand(1,100);
inds = find(x>0.4 & x0.4 returns a vector with 1 where true and 0 where false x
5/25/2018 Mit Matlab Course
94/205
Given x= sin(linspace(0,10*pi,100)), how many of theentries are positive?
Using a loop and if/elsecount=0;
for n=1:length(x)
ifx(n)>0count=count+1;
end
end
Being more clevercount=length(find(x>0));
length(x) Loop time Find time
100 0.01 0
10,000 0.1 0
100,000 0.22 0
1,000,000 1.5 0.04
Avoid loops like the plague!
Built-in functions will make it faster to write and execute
Efficient Code
Avoid loops whenever possible
5/25/2018 Mit Matlab Course
95/205
Avoid loops whenever possible This is referred to as vectorization
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops For example:a=rand(1,100);
b=zeros(1,100);
for n=1:100
if n==1
b(n)=a(n);
else
b(n)=a(n-1)+a(n);
end
endSlow and complicated
a=rand(1,100);
b=[0 a(1:end-1)]+a;
Efficient and clean
Exercise: Vectorization
Alter your factorial program to work WITHOUT a loop Use
5/25/2018 Mit Matlab Course
96/205
Alter your factorial program to work WITHOUT a loop. Useprod
function a=factorial(N)
a=prod(1:N);
You can tic/toc to see how much faster this is than the
loop!
BUTDont ALWAYS avoid loopsOver-vectorizing code can obfuscate it, i.e. you wont be
able to understand or debug it laterSometime a loop is the right thing to do, it is clearer andsimple
End of Lecture 2
(1) Plotting Continued
5/25/2018 Mit Matlab Course
97/205
(1) Plotting Continued
(2) Scripts
(3) Functions(4) Flow Control
Vectorization makescoding fun!
MIT OpenCourseWare
http://ocw.mit.edu
6.094 Introduction to MATLAB
January (IAP) 2009
http://ocw.mit.edu/http://ocw.mit.edu/5/25/2018 Mit Matlab Course
98/205
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
6 094Int od ction to P og amming in MATLAB
http://ocw.mit.edu/termshttp://ocw.mit.edu/termshttp://ocw.mit.edu/terms5/25/2018 Mit Matlab Course
99/205
6.094Introduction to Programming in MATLAB
Lecture 3 : Solving Equations and Curve Fitting
Sourav Dey
Danilo epanoviAnkit PatelPatrick Ho
IAP 2009
Outline
(1) Linear Algebra
5/25/2018 Mit Matlab Course
100/205
(1) Linear Algebra
(2) Polynomials
(3) Optimization(4) Differentiation/Integration
(5) Differential Equations
Systems of Linear Equations
Given a system of linear equations MATLAB makes linearalgebra fun!
5/25/2018 Mit Matlab Course
101/205
Given a system of linear equations x+2y-3z=5 -3x-y+z=-8 x-y+z=0
Construct matrices so the system is described by Ax=bA=[1 2 -3;-3 -1 1;1 -1 1];b=[5;-8;0];
And solve with a single line of code!x=A\b; x is a 3x1 vector containing the values of x, y, and z
The \ will work with square or rectangular systems. Gives least squares solution for rectangular systems. Solutiondepends on whether the system is over or underdetermined.
MATLAB makes linearalgebra fun!
More Linear Algebra
Given a matrix
5/25/2018 Mit Matlab Course
102/205
Given a matrixmat=[1 2 -3;-3 -1 1;1 -1 1];
Calculate the rank of a matrixr=rank(mat);
the number of linearly independent rows or columns
Calculate the determinantd=det(mat);mat must be square if determinant is nonzero, matrix is invertible
Get the matrix inverseE=inv(mat);
if an equation is of the form A*x=b with A a square matrix,x=A\b is the same as x=inv(A)*b
Matrix Decompositions
MATLAB has built-in matrix decomposition methods
5/25/2018 Mit Matlab Course
103/205
MATLAB has built in matrix decomposition methods
The most common ones are
[V,D]=eig(X) Eigenvalue decomposition
[U,S,V]=svd(X)
Singular value decomposition[Q,R]=qr(X)
QR decomposition
Exercise: Linear Algebra
Solve the following systems of equations:
5/25/2018 Mit Matlab Course
104/205
So e t e o o g syste s o equat o s
System 1: x+4y=34 -3x+y=2
System 2: 2x-2y=4 -x+y=3 3x+4y = 2
Exercise: Linear Algebra
Solve the following systems of equations:
5/25/2018 Mit Matlab Course
105/205
g y q
System 1: x+4y=34 -3x+y=2
System 2: 2x-2y=4 -x+y=3 3x+4y = 2
A=[1 4;-3 1];
b=[34;2];rank(A)
x=inv(A)*b;
A=[2 -2;-1 1;3 4];
b=[4;3;2];
rank(A)
rectangular matrixx1=A\b;
gives least squares solution
A*x1
Outline
(1) Linear Algebra
5/25/2018 Mit Matlab Course
106/205
( ) g
(2) Polynomials
(3) Optimization(4) Differentiation/Integration
(5) Differential Equations
Polynomials
Many functions can be well described by a high-orderl i l
5/25/2018 Mit Matlab Course
107/205
y y gpolynomial
MATLAB represents a polynomials by a vector of coefficients if vector P describes a polynomial ax3+bx2+cx+d
P=[1 0 -2] represents the polynomial x2-2
P=[2 0 0 0] represents the polynomial 2x3
P(1) P(2) P(3) P(4)
Polynomial Operations
P is a vector of length N+1 describing an N-th order polynomialT t th t f l i l
5/25/2018 Mit Matlab Course
108/205
To get the roots of a polynomialr=roots(P)
r is a vector of length N
Can also get the polynomial from the rootsP=poly(r)
r is a vector length N
To evaluate a polynomial at a pointy0=polyval(P,x0)
x0 is a single value; y0 is a single value
To evaluate a polynomial at many pointsy=polyval(P,x)
x is a vector; y is a vector of the same size
Polynomial Fitting
MATLAB makes it very easy to fit polynomials to data
5/25/2018 Mit Matlab Course
109/205
Given data vectors X=[-1 0 2] and Y=[0 -1 3]
p2=polyfit(X,Y,2); finds the best second order polynomial that fits the points
(-1,0),(0,-1), and (2,3) see help polyfit for more information
plot(X,Y,o, MarkerSize, 10);hold on;
x = linspace(-2,2,1000);
plot(x,polyval(p2,x), r--);
Exercise: Polynomial Fitting
Evaluate x^2 over x=-4:0.1:4 and save it as y.
5/25/2018 Mit Matlab Course
110/205
Add random noise to these samples. Use randn. Plot thenoisy signal with . markers
fit a 2nd degree polynomial to the noisy data
plot the fitted polynomial on the same plot, using the samex values and a red line
Exercise: Polynomial Fitting
Evaluate x^2 over x=-4:0.1:4 and save it as y. 4 0 1 4
5/25/2018 Mit Matlab Course
111/205
x=-4:0.1:4;
y=x.^2;
Add random noise to these samples. Use randn. Plot thenoisy signal with . markersy=y+randn(size(y));
plot(x,y,.);
fit a 2nd degree polynomial to the noisy data[p]=polyfit(x,y,2);
plot the fitted polynomial on the same plot, using the samex values and a red linehold on;
plot(x,polyval(p,x),r)
Outline
(1) Linear Algebra
5/25/2018 Mit Matlab Course
112/205
(2) Polynomials
(3) Optimization(4) Differentiation/Integration
(5) Differential Equations
Nonlinear Root Finding
Many real-world problems require us to solve f(x)=0 Can use fzero to calculate roots for any arbitrary function
5/25/2018 Mit Matlab Course
113/205
Can use fzero to calculate roots for any arbitrary function
fzero needs a function passed to it. We will see this more and more as we delve into solvingequations.
Make a separate function filex=fzero('myfun',1)
x=fzero(@myfun,1)
1 specifies apoint close tothe root
Courtesy of The MathWorks, Inc. Used with permission.
Minimizing a Function
fminbnd: minimizing a function over a bounded interval x=fminbnd('myfun' -1 2);
5/25/2018 Mit Matlab Course
114/205
x=fminbnd( myfun , 1,2);
myfun takes a scalar input and returns a scalar outputmyfun(x) will be the minimum of myfun for -1x 2
fminsearch: unconstrained intervalx=fminsearch('myfun',.5)
finds the local minimum of myfun starting at x=0.5
Anonymous Functions
You do not have to make a separate function file
5/25/2018 Mit Matlab Course
115/205
Instead, you can make an anonymous function
x=fzero(@(x)(cos(exp(x))+x^2-1), 1 );
x=fminbnd(@(x) (cos(exp(x))+x^2-1),-1,2);
input function to evaluate
Optimization Toolbox
If you are familiar with optimization methods, use theoptimization toolbox
5/25/2018 Mit Matlab Course
116/205
p
Useful for larger, more structured optimization problems
Sample functions (see help for more info)linprog
linear programming using interior point methodsquadprog
quadratic programming solver
fmincon constrained nonlinear optimization
Exercise: Min-Finding
Find the minimum of the function f(x) =cos(4*x).*sin(10*x).*exp(-abs(x)) over the range pi to
5/25/2018 Mit Matlab Course
117/205
( ) ( ) p( ( )) g ppi. Use fminbnd. Is your answer really the minimumover this range?
Exercise: Min-Finding
Find the minimum of the function f(x) =cos(4*x).*sin(10*x).*exp(-abs(x)) over the range pi to
5/25/2018 Mit Matlab Course
118/205
( ) ( ) p( ( )) g ppi. Use fminbnd. Is your answer really the minimumover this range?
function y = myFun(x)
y=cos(4*x).*sin(10*x).*exp(-abs(x));
fminbnd(myFun, -pi, pi);
Outline
(1) Linear Algebra
(2) P l i l
5/25/2018 Mit Matlab Course
119/205
(2) Polynomials
(3) Optimization(4) Differentiation/Integration
(5) Differential Equations
Numerical Differentiation
MATLAB can 'differentiate' numericallyx=0:0.01:2*pi; 0.6
0.8
1
5/25/2018 Mit Matlab Course
120/205
y=sin(x);
dydx=diff(y)./diff(x);
diff computes the first difference
Can also operate on matricesmat=[1 3 5;4 8 6];
dm=diff(mat,1,2)
first difference of mat along the 2nd dimension, dm=[2 2;4 -2] see help for more details
2D gradient[dx,dy]=gradient(mat);
0 100 200 300 400 500 600 700-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
Numerical Integration
MATLAB contains common integration methods
5/25/2018 Mit Matlab Course
121/205
Adaptive Simpson's quadrature (input is a function)
q=quad('derivFun',0,10); q is the integral of the function derivFun from 0 to 10
q2=quad(@sin,0,pi)
q2 is the integral of sin from 0 to pi
Trapezoidal rule (input is a vector)x=0:0.01:pi;
z=trapz(x,sin(x));
z is the integral of sin(x) from 0 to piz2=trapz(x,sqrt(exp(x))./x)
z2 is the integral of from 0 to pixe x
Outline
(1) Linear Algebra
(2) Pol nomials
5/25/2018 Mit Matlab Course
122/205
(2) Polynomials
(3) Optimization(4) Differentiation/Integration
(5) Differential Equations
ODE Solvers: Method
Given a differential equation, the solution can be found byintegration:
5/25/2018 Mit Matlab Course
123/205
Evaluate the derivative at a point and approximate by straight line Errors accumulate! Variable timestep can decrease the number of iterations
ODE Solvers: MATLAB
MATLAB contains implementations of common ODE solvers
5/25/2018 Mit Matlab Course
124/205
Using the correct ODE solver can save you lots of time andgive more accurate resultsode23
Low-order solver. Use when integrating over small intervalsor when accuracy is less important than speed
ode45High order (Runge-Kutta) solver. High accuracy and
reasonable speed. Most commonly used.ode15s
Stiff ODE solver (Gear's algorithm), use when the diff eq'shave time constants that vary by orders of magnitude
ODE Solvers: Standard Syntax
To use standard options and variable time step[t,y]=ode45('myODE',[0,10],[1;0])
5/25/2018 Mit Matlab Course
125/205
Inputs:
ODE function name (or anonymous function). This functiontakes inputs (t,y), and returns dy/dt Time interval: 2-element vector specifying initial and final
time Initial conditions: column vector with an initial condition for
each ODE. This is the first input to the ODE function Outputs:
t contains the time points y contains the corresponding values of the integrated fcn.
ODE integrator:23, 45, 15sODE function Time range
Initial conditions
ODE Function
The ODE function must return the value of the derivative ata given time and function value
5/25/2018 Mit Matlab Course
126/205
Example: chemical reaction Two equations
ODE file:
y has [A;B] dydt has
[dA/dt;dB/dt]
A B
10
50
10 50
10 50
dAA B
dt
dB A Bdt
= +
=
Courtesy of The MathWorks, Inc.
Used with permission.
ODE Function: viewing results
To solve and plot the ODEs on the previous slide:[t,y]=ode45('chem',[0 0.5],[0 1]);
5/25/2018 Mit Matlab Course
127/205
assumes that only chemical B exists initiallyplot(t,y(:,1),'k','LineWidth',1.5);
hold on;
plot(t,y(:,2),'r','LineWidth',1.5);
legend('A','B');
xlabel('Time (s)');
ylabel('Amount of chemical (g)');
title('Chem reaction');
ODE Function: viewing results
The code on the previous slide produces this figure
5/25/2018 Mit Matlab Course
128/205
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.50
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
Time (s)
Amount
ofchemical(g)
Chem reaction
A
B
Higher Order Equations
Must make into a system of first-order equations to useODE solvers
Nonlinear is OK!
5/25/2018 Mit Matlab Course
129/205
Pendulum example:
( )
( )
( )
0g sinL
gsin
L
let
gsin
L
x
dx
dt
+ =
=
=
=
=
=
&&
&&
&
&
v
v &
&
Courtesy of The MathWorks, Inc. Used with permission.
Plotting the Output
We can solve for the position and velocity of the pendulum:[t,x]=ode45('pendulum',[0 10],[0.9*pi 0]);
d l i l t ti l ( t t )
5/25/2018 Mit Matlab Course
130/205
assume pendulum is almost vertical (at top)plot(t,x(:,1));
hold on;
plot(t,x(:,2),'r');
legend('Position','Velocity');
0 1 2 3 4 5 6 7 8 9 10-8
-6
-4
-2
0
2
4
6
8
Position
Velocity
Position in terms ofangle (rad)
Velocity (m/s)
Plotting the Output
Or we can plot in the phase plane:plot(x(:,1),x(:,2));
l b l('P iti ')
5/25/2018 Mit Matlab Course
131/205
xlabel('Position');
yLabel('Velocity');
The phase plane is just a plot of one variable versus theother:
-3 -2 -1 0 1 2 3-8
-6
-4
-2
0
2
4
6
8
Position
Velocity
Velocity is greatestwhen theta=0
Velocity=0 whentheta is the greatest
ODE Solvers: Custom Options
MATLAB's ODE solvers use a variable timestep Sometimes a fixed timestep is desirable
[t ] ode45('chem' [0 0 001 0 5] [0 1])
5/25/2018 Mit Matlab Course
132/205
[t,y]=ode45('chem',[0:0.001:0.5],[0 1]);
Specify the timestep by giving a vector of times The function will be evaluated at the specified points Fixed timestep is usually slower (if timestep is small) and
possibly inaccurate (if timestep is too large)
You can customize the error tolerances using odesetoptions=odeset('RelTol',1e-6,'AbsTol',1e-10);
[t,y]=ode45('chem',[0 0.5],[0 1],options);
This guarantees that the error at each step is less thanRelTol times the value at that step, and less than AbsTol
Decreasing error tolerance can considerably slow the solver
See doc odeset for a list of options you can customize
Exercise: ODE
Use ODE45 to solve this differential equation on the ranget=[0 10], with initial condition y(0) = 10: dy/dt=-t*y/10.Plot the result.
5/25/2018 Mit Matlab Course
133/205
Plot the result.
Exercise: ODE
Use ODE45 to solve this differential equation on the ranget=[0 10], with initial condition y(0) = 10: dy/dt=-t*y/10.Plot the result.
5/25/2018 Mit Matlab Course
134/205
function dydt=odefun(t,y)
dydt=-t*y/10;
[t,y]=ode45(odefun,[0 10],10);
plot(t,y);
End of Lecture 3
(1) Linear Algebra(2) Polynomials
5/25/2018 Mit Matlab Course
135/205
( ) y
(3) Optimization(4) Differentiation/Integration
(5) Differential Equations
We're almost done!
Issues with ODEs
Stability and accuracy if step size is too large, solutions might blow up if step size is too small, requires a long time to solve
5/25/2018 Mit Matlab Course
136/205
if step size is too small, requires a long time to solve use odeset to control errors
decrease error tolerances to get more accurateresults
increase error tolerances to speed up computation
(beware of instability!) Main thing to remember about ODEs Pick the most appropriate solver for your problem If ode45 is taking too long, try ode15s
MIT OpenCourseWare
http://ocw.mit.edu
6.094 Introduction to MATLAB
January (IAP) 2009
For information about citing these materials or our Terms of Use visit: http://ocw mit edu/terms
http://ocw.mit.edu/http://ocw.mit.edu/termshttp://ocw.mit.edu/termshttp://ocw.mit.edu/termshttp://ocw.mit.edu/5/25/2018 Mit Matlab Course
137/205
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
6.094
Introduction to Programming in MATLAB
http://ocw.mit.edu/termshttp://ocw.mit.edu/termshttp://ocw.mit.edu/terms5/25/2018 Mit Matlab Course
138/205
Lecture 4: Advanced Methods
Sourav Dey
Danilo
epanovi
Ankit PatelPatrick Ho
IAP 2009
Outline
(1) Probability and Statistics(2) Data Structures
5/25/2018 Mit Matlab Course
139/205
(3) Images and Animation(4) Debugging
(5) Symbolic Math
(6) Other Toolboxes
Statistics
Whenever analyzing data, you have to compute statisticsscores = 100*rand(1,100);
5/25/2018 Mit Matlab Course
140/205
Built-in functionsmean, median, mode
To group data into a histogram
hist(scores,5:10:95);makes a histogram with bins centered at 5, 15, 2595
N=histc(scores,0:10:100);
returns the number of occurrences between the specifiedbin edges 0 to
5/25/2018 Mit Matlab Course
141/205
rand
draws from the uniform distribution from 0 to 1randn
draws from the standard normal distribution (Gaussian)
random can give random numbers from many more distributions see doc random for help the docs also list other specific functions
You can also seed the random number generatorsrand(state,0)
Changing Mean and Variance
We can alter the given distributionsy=rand(1,100)*10+5; gives 100 uniformly distributed numbers between 5 and 15
5/25/2018 Mit Matlab Course
142/205
y=floor(rand(1,100)*10+6);
gives 100 uniformly distributed integers between 10 and15. floor or ceil is better to use here than round
y=randn(1,1000)y2=y*5+8
increases std to 5 and makes the mean 8-25 -20 -15 -10 -5 0 5 10 15 20 250
50
100
150
200
250
300
350
400
-25 -20 -15 -10 -5 0 5 10 15 20 250
10
20
30
40
50
60
70
80
90
Exercise: Probability
We will simulate Brownian motion in 1 dimension. Call the scriptbrown Make a 10,000 element vector of zeros Write a loop to keep track of the particles position at each time
5/25/2018 Mit Matlab Course
143/205
Start at 0. To get the new position, pick a random number, and if
its 0.5, go right. Store each new position inthe kth position in the vector Plot a 50 bin histogram of the positions.
Exercise: Probability
We will simulate Brownian motion in 1 dimension. Call the scriptbrown Make a 10,000 element vector of zeros Write a loop to keep track of the particles position at each time
5/25/2018 Mit Matlab Course
144/205
Start at 0. To get the new position, pick a random number, and if
its 0.5, go right. Store each new position inthe kth position in the vector Plot a 50 bin histogram of the positions.
x=zeros(10000,1);
for n=2:10000 if rand
5/25/2018 Mit Matlab Course
145/205
(3) Images and Animation(4) Debugging
(5) Symbolic Math
(6) Other Toolboxes
Advanced Data Structures
We have used 2D matricesCan have n-dimensions Every element must be the same type (ex. integers,
doubles characters )
5/25/2018 Mit Matlab Course
146/205
doubles, characters)
Matrices are space-efficient and convenient for calculation
Sometimes, more complex data structures are moreappropriate
Cell array: it's like an array, but elements don't have to bethe same type
Structs: can bundle variable names and values into onestructure
Like object oriented programming in MATLAB
Cells: organization
A cell is just like a matrix, but each field can containanything (even other matrices):
3x3 Matrix 3x3 Cell Array
5/25/2018 Mit Matlab Course
147/205
One cell can contain people's names, ages, and the ages oftheir children
To do the same with matrices, you would need 3 variables
and padding
3x3 Matrix
1.2 -3 5.5
-2.4 15 -10
7.8 -1.1 4
3x3 Cell Array
32
27 1
18
J o h n
M a r y
L e o
2
4
[ ]
Cells: initialization
To initialize a cell, specify the sizea=cell(3,10); a will be a cell with 3 rows and 10 columns
5/25/2018 Mit Matlab Course
148/205
or do it manually, with curly braces {}c={'hello world',[1 5 6 2],rand(3,2)};
c is a cell with 1 row and 3 columns
Each element of a cell can be anything
To access a cell element, use curly braces {}
a{1,1}=[1 3 4 -10];a{2,1}='hello world 2';
a{1,2}=c{3};
Structs
Structs allow you to name and bundle relevant variables Like C-structs, which are objects with fields
To initialize an empty struct:
5/25/2018 Mit Matlab Course
149/205
p y
s=struct([]); size(s) will be 1x1 initialization is optional but is recommended when using large
structs
To add fieldss.name = 'Jack Bauer';
s.scores = [95 98 67];
s.year = 'G3'; Fields can be anything: matrix, cell, even struct Useful for keeping variables together
For more information, see doc struct
Struct Arrays
To initialize a struct array, give field, values pairsppl=struct('name',{'John','Mary','Leo'},...'age',{32,27,18},'childAge',{[2;4],1,[]});
size(s2) 1x3
5/25/2018 Mit Matlab Course
150/205
size(s2)=1x3
every cell must have the same sizeperson=ppl(2);
person is now a struct with fields name, age, children
the values of the fields are the second index into each cellperson.name
returns 'Mary' ppl ppl(1) ppl(2) ppl(3)
name: 'John' 'Mary' 'Leo'
age: 32 27 18
childAge: [2;4] 1 []
Structs: access
To access 1x1 struct fields, give name of the fieldstu=s.name;scor=s.scores;
1 1 t t f l h i i bl t
5/25/2018 Mit Matlab Course
151/205
1x1 structs are useful when passing many variables to a
function. put them all in a struct, and pass the struct
To access nx1 struct arrays, use indices
person=ppl(2); person is a struct with name, age, and child age
personName=ppl(2).name;
personName is 'Mary'a=[ppl.age];
a is a 1x3 vector of the ages
Exercise: Cells
Write a script called sentGen Make a 3x2 cell, and put peoples names into the firstcolumn, and adjectives into the second column
Pick two random integers (values 1 to 3)
5/25/2018 Mit Matlab Course
152/205
Pick two random integers (values 1 to 3)
Display a sentence of the form [name] is [adjective]. Run the script a few times
Exercise: Cells
Write a script called sentGen Make a 3x2 cell, and put peoples names into the firstcolumn, and adjectives into the second column
Pick two random integers (values 1 to 3)
5/25/2018 Mit Matlab Course
153/205
Pick two random integers (values 1 to 3)
Display a sentence of the form [name] is [adjective]. Run the script a few times
c=cell(3,2);c{1,1}=John;c{2,1}=Mary-Sue;c{3,1}=Gomer;
c{1,2}=smart;c{2,2}=blonde;c{3,2}=hot
r1=ceil(rand*3);r2=ceil(rand*3);disp([ c{r1,1}, is , c{r2,2}, . ]);
Outline
(1) Probability and Statistics(2) Data Structures
(3) Images and Animation
5/25/2018 Mit Matlab Course
154/205
(3) Images and Animation
(4) Debugging
(5) Symbolic Math
(6) Other Toolboxes
Importing/Exporting Images
Images can be imported into matlabim=imread('myPic.jpg');
MATLAB supports almost all image formats
5/25/2018 Mit Matlab Course
155/205
MATLAB supports almost all image formatsjpeg, tiff, gif, bmp, png, hdf, pcx, xwd, ico, cur, ras, pbm,
pgm, ppm see help imread for a full list and details
To write an image, give an rgb matrix or indices andcolormapimwrite(mat,jet(256),'test.jpg','jpg');
see help imwrite for more options
Animations
MATLAB makes it easy to capture movie frames and playthem back automatically
The most common movie formats are:
5/25/2018 Mit Matlab Course
156/205
The most common movie formats are: avi animated gif
Avi good when you have natural frames with lots of colors andfew clearly defined edges
Animated gif
Good for making movies of plots or text where only a fewcolors exist (limited to 256) and there are well-definedlines
Making Animations
Plot frame by frame, and pause in betweenclose allfor t=1:30
imagesc(rand(200));
5/25/2018 Mit Matlab Course
157/205
imagesc(rand(200));
colormap(gray);
pause(.5);
end
Saving Animations as Movies
A movie is a series of captured framesclose allfor n=1:30
imagesc(rand(200));
5/25/2018 Mit Matlab Course
158/205
imagesc(rand(200));
colormap(gray);
M(n)=getframe;
end
To play a movie in a figure windowmovie(M,2,30);
Loops the movie 2 times at 30 frames per second
To save as an .avi file on your hard drivemovie2avi(M,'testMovie.avi','FPS',30);
See book appendix or docs for more information
Handles
Every graphics object has a handleh=plot(1:10,rand(1,10)); gets the handle for the plotted line
h2=gca;
5/25/2018 Mit Matlab Course
159/205
g ;
gets the handle for the current axish3=gcf;
gets the handle for the current figure
To see the current property values, use getget(h);yVals=get(h,'YData');
To change the properties, use setset(h2,'FontName','Arial','XScale','log');
set(h,'LineWidth',1.5,'Marker','*');
Everything you see in a figure is completely customizable
through handles
Outline
(1) Probability and Statistics(2) Data Structures
(3) Images and Animation
5/25/2018 Mit Matlab Course
160/205
(3) Images and Animation
(4) Debugging
(5) Symbolic Math
(6) Other Toolboxes
display
When debugging functions, use disp to print messagesdisp('starting loop')disp('loop is over')
disp prints the given string to the command window
5/25/2018 Mit Matlab Course
161/205
p p g g
It's also helpful to show variable values
disp(strcat(['loop iteration ',num2str(n)])); strcat concatenates the given stringsSometimes it's easier to just remove some semicolons
Debugging
To use the debugger, set breakpointsClick on next to line numbers in MATLAB files Each red dot that appears is a breakpointRun the program The program pauses when it reaches a breakpoint
5/25/2018 Mit Matlab Course
162/205
The program pauses when it reaches a breakpointUse the command window to probe variablesUse the debugging buttons to control debugger
Two breakpoints
Where the program is now
Clear breakpoint
Step to next
Stop execution; exit
Courtesy of The MathWorks, Inc. Used with permission.
Exercise: Debugging
Use the debugger to fix the errors in the following code:
5/25/2018 Mit Matlab Course
163/205
Courtesy of The MathWorks, Inc. Used with permission.
Performance Measures
It can be useful to know how long your code takes to run To predict how long a loop will take To pinpoint inefficient code
5/25/2018 Mit Matlab Course
164/205
You can time operations using tic/toc:tic
CommandBlock1
a=toc;CommandBlock2
b=toc;
tic resets the timer Each toc returns the current value in secondsCan have multiple tocs per tic
Performance Measures
For more complicated programs, use the profilerprofile on Turns on the profiler. Follow this with function calls
profile viewer
5/25/2018 Mit Matlab Course
165/205
Displays gui with stats on how long each subfunction took
Courtesy of The MathWorks, Inc. Used with permission.
Outline
(1) Probability and Statistics(2) Data Structures
(3) Images and Animation
5/25/2018 Mit Matlab Course
166/205
( ) g
(4) Debugging
(5) Symbolic Math
(6) Other Toolboxes
What are Toolboxes?
Toolboxes contain functions specific to a particular field for example: signal processing, statistics, optimization
It's generally more efficient to use MATLAB's toolboxes
5/25/2018 Mit Matlab Course
167/205
rather than redefining the functions yourself saves coding/debugging time some functions are compiled, so they run fasterHOWEVER there may be mistakes in MATLABs functions
and there may also be surprises
MATLAB on Athena contains all the toolboxes
Here are a few particularly useful ones for EECS
Symbolic Toolbox
Dont do nasty calculations by hand! Symbolics vs. Numerics
Advantages Disadvantages
5/25/2018 Mit Matlab Course
168/205
Symbolic Analytical solutionsLets you intuit
things aboutsolution form
Sometimes can't besolvedCan be overlycomplicated
Numeric Always get asolution
Can make solutionsaccurateEasy to code
Hard to extract adeeper understanding
Num. methodssometimes failCan take a while tocompute
Symbolic Variables
Symbolic variables are a type, like double or char
To make symbolic variables, use syma=sym('1/3');
5/25/2018 Mit Matlab Course
169/205
b=sym('4/5');
fractions remain as fractionsc=sym('c','positive');
can add tags to narrow down scope see help sym for a list of tags
Or use symssyms x y real
shorthand for x=sym('x','real'); y=sym('y','real');
Symbolic Expressions
Multiply, add, divide expressionsd=a*b does 1/3*4/5=4/15;
5/25/2018 Mit Matlab Course
170/205
expand((a-c)^2);
multiplies out
factor(ans)
factors the expression
Cleaning up Symbolic Statements
pretty(ans)
makes it look nicer
collect(3*x+4*y-1/3*x^2-x+3/2*y)
5/25/2018 Mit Matlab Course
171/205
collects terms
simplify(cos(x)^2+sin(x)^2)
simplifies expressions
subs(c^2,c,5)
Replaces variables with numbers
or expressions
subs(c^2,c,x/7)
ans=
25
ans=
1/ 49*x 2
More Symbolic Operations
We can do symbolics with matrices toomat=sym('[a b;c d]');
mat2=mat*[1 3;4 -2];
5/25/2018 Mit Matlab Course
172/205
compute the productd=det(mat)
compute the determinant
i=inv(mat) find the inverse
You can access symbolic matrix elements as beforei(1,2)
Exercise: Symbolics
The equation of a circle of radius r centered at (a,b) isgiven by: (x-a)^2 + (y-b)^2 = r^2.
Expand this equation into the form Ax^2 + Bx+Cxy + Dy +Ey^2 = F and find the expression for the coefficients in
5/25/2018 Mit Matlab Course
173/205
terms of a,b, and r.
Exercise: Symbolics
The equation of a circle of radius r centered at (a,b) isgiven by: (x-a)^2 + (y-b)^2 = r^2.
Expand this equation into the form Ax^2 + Bx+Cxy + Dy +Ey^2 = F and find the expression for the coefficients in
5/25/2018 Mit Matlab Course
174/205
terms of a,b, and r.
syms a b r x y
pretty(expand((x-a).^2 + (y-b).^2))
Outline
(1) Probability and Statistics(2) Data Structures
(3) Images and Animation
5/25/2018 Mit Matlab Course
175/205
(4) Debugging
(5) Symbolic Math
(6) Other Toolboxes
Signal Processing Toolbox
MATLAB is often used for signal processing (fft) What you can do:
filter design statistical signal processing
L l t f
5/25/2018 Mit Matlab Course
176/205
Laplace transforms
Related ToolboxesCommunicationsWaveletsRF Image Processing
Control System Toolbox
The control systems toolbox contains functions helpful foranalyzing systems with feedback
Simulation of LTI system function
Di t ti ti ti
5/25/2018 Mit Matlab Course
177/205
Discrete time or continuous time You will be exposed to it in 6.003 Can easily study step response, etc. modal analysis.
Related toolboxes:System IdentificationRobust Control modern control theoryModel Predictive Control
Statistics Toolbox
For hardcore statistics and data-analysis Principal component analysis Independent component analysis Tests of significance (chi squared, t-tests)
5/25/2018 Mit Matlab Course
178/205
Related ToolboxesSpline for fittingBioinformaticsNeural Networks
Optimization Toolbox
For more hardcore optimization problems that occur inOR, business, engineering
linear programming interior point methods
quadratic methods
5/25/2018 Mit Matlab Course
179/205
quadratic methods
SIMULINK
Interactive graphical environment Block diagram based MATLAB add-on environment Design, simulate, implement, and test control, signal
processing, communications, and other time-varying
systems
5/25/2018 Mit Matlab Course
180/205
systems
Courtesy of The MathWorks, Inc. Used with permission.
Central File Exchange
The website the MATLAB Central File Exchange!! Lots of people's code is there Tested and rated use it to expand MATLAB's functionality
http://www mathworks com/matlabcentral/
5/25/2018 Mit Matlab Course
181/205
http://www.mathworks.com/matlabcentral/
MATLAB Final Exam
Brownian Motion stop-animation integrating loops,randomization, visualization
Make a function brown2d(numPts), where numPts is the
number of points that will be doing Brownian motion
5/25/2018 Mit Matlab Course
182/205
number of points that will be doing Brownian motion Plot the position in (x,y) space of each point (start initially
at 0,0). Set the x and y limits so theyre consistent. After each timestep, move each x and y coordinate by
randn*.1 Pause by 0.001 between frames Turn on the DoubleBuffer property to remove flicker
set(gcf,DoubleBuffer,on);
Ask us for help if needed!
End of Lecture 4
(1) Data Structures(2) Symbolics
(3) Probability
(4) Toolboxes
5/25/2018 Mit Matlab Course
183/205
(4) Toolboxes
THE END
Monte-Carlo Simulation
A simple way to model complex stochastic systems Use random numbers to control state changes
BA60
472 2
20 20
5/25/2018 Mit Matlab Course
184/205
This system represents a complex reaction
The numbers by the arrows show the propensity of thesystem to go from one state to another If you start with 1 molecule of A, how does the system
behave with time?
E
D C
60
60
60 47 47
47
2
2
2
20 20
Example: Monte-Carlo
This MATLAB file will track the behavior of the molecule
5/25/2018 Mit Matlab Course
185/205
Courtesy of The MathWorks, Inc. Used with permission.
Example: Monte-Carlo
We can run the code 1000 times to simulate 1000 moleculess=zeros(200,5);
for n=1:1000
st=MC(200);
for state=0:4 s(: state+1)= s(: state+1)+(st==state);
5/25/2018 Mit Matlab Course
186/205
s(:,state+1)= s(:,state+1)+(st==state);
end
end
0 20 40 60 80 100 120 140 160 180 2000
100
200
300
400
500
600
700
800
900
1000A
0 20 40 60 80 100 120 140 160 180 2000
50
100
150
200
250
300
350
400
450B
0 20 40 60 80 100 120 140 160 180 2000
50
100
150
200
250
300
350C
0 20 40 60 80 100 120 140 160 180 2000
50
100
150
200
250
300
350
400D
0 20 40 60 80 100 120 140 160 180 2000
100
200
300
400
500
600
700
800
900
1000E
MIT OpenCourseWarehttp://ocw.mit.edu
6.094 Introduction to MATLAB
January (IAP) 2009
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
http://ocw.mit.edu/http://ocw.mit.edu/termshttp://ocw.mit.edu/termshttp://ocw.mit.edu/termshttp://ocw.mit.edu/5/25/2018 Mit Matlab Course
187/205
6.094
Introduction to Programming in MATLAB
Lecture 5: Simulink
5/25/2018 Mit Matlab Course
188/205
Sourav DeyDanilo epanovi
Ankit PatelPatrick Ho
IAP 2009
What is Simulink?
A model-based equation solver Some analysis packages (ANSYS, Multisim) have
built in equations modeling complex engineeringproblems.
5/25/2018 Mit Matlab Course
189/205
problems.Save lots of timeCan only be used for tackling specific problems
Simulink lets you build a GUI-based model andsimulates the result.
Unlimited complexity (constrained by runtime andmemory)
Adaptable for any field
Downside? You have to do the modeling work
Getting Started
Create a new file
Examine the Simulink Library Browser
Click on a library:Sources
5/25/2018 Mit Matlab Course
190/205
y
Drag a block into Simulink:Constant
Visualize the block by going intoSinks
Drag aScopeinto Simulink
Connections
Click on the carat/arrow on the right of theconstant box
Drag the line to the scopeYoull get a hint saying you can quickly connect
5/25/2018 Mit Matlab Course
191/205
Drag the line to the scopeYoull get a hint saying you can quickly connect
blocks by hitting CtrlConnections between lines represent signals
Click the play button
Double click on the scope.This will open up a chart of the variable over the
simulation time
Simulink Math
Everything is visual in Simulink!
Click on the library Continuous
Drag the integrator block between the constant andthe scope
5/25/2018 Mit Matlab Course
192/205
p
Play and click on scope.
What happens?
Simulink has a built in ODE solverThe equation that represents your model is solved by
SimulinkWeve represented
Behind the curtain
Go toSimulation->Configuration Parameters
at the top menuSee ode45? Change the solver type here
5/25/2018 Mit Matlab Course
193/205
Courtesy of The MathWorks, Inc. Used with permission.
So whats going on?
The toolboxes Simulink provides you are full ofmodeling tools
By selecting components that correspond to yourmodel, you can design a simulation
5/25/2018 Mit Matlab Course
194/205
y g p p y, y g
Toolboxes
MathTakes the signal and performs a math operation
Add, subtract, round, multiply, gain, angle
ContinuousAdds differential equations to the system
5/25/2018 Mit Matlab Course
195/205
Integrals, Derivatives, Transfer Functions,
State Space
DiscontinuitiesAdds nonlinearities to your system
DiscreteSimulates discrete difference equationsUseful for digital systems
Building systems
Sources Step input, white noise, custom input, sine
wave, ramp input,
Provides input to your system
Sinks
5/25/2018 Mit Matlab Course
196/205
Scope: Outputs to plot
simout: Outputs to a MATLAB vector on workspace
MATLAB mat file
Modifying Blocks
Right click on the block, select the Parameters item
corresponding to the item type Transfer Function:Numerator on
first row
Denominator on
5/25/2018 Mit Matlab Course
197/205
second row
Summing Junction: List of signs
determines
inputs tojunction
Not shown:
Sampling time rowCourtesy of The MathWorks, Inc. Used with permission.
Modifying Scopes
Within the scope:Autoscale fits the axes
to the curve automatically
Axes properties lets you
customize the axes
5/25/2018 Mit Matlab Course
198/205
Changing the number of axes:
Left click on icon
Change the number
of axes field
Courtesy of The MathWorks, Inc. Used with permission.
Courtesy of The MathWorks,
Inc. Used with permission.
Courtesy of The MathWorks, Inc. Used with permission.
First System
Drag a summingjunction between theconstant andintegrator
5/25/2018 Mit Matlab Course
199/205
Change the signs to|+-
Click on the opencarat under the minussign and connect it tothe integrator output
Creating Subsystems
Drag a box around the
parts of the subsystemSumming JunctionIntegrator
Right click and selectcreate subsystem
5/25/2018 Mit Matlab Course
200/205
Double click thesubsystem:
The parts are nowinside
Whats the system dowhen you run it?
Example Systems
ODE
d3
y/dt3
+ a*d2
y/dt2
+b* dy/dt + c*y = F
Classical Control System
5/25/2018 Mit Matlab Course
201/205
Courtesy of The MathWorks, Inc. Used with permission.
Courtesy of The
MathWorks, Inc.Used with permission.
Example: Nervous System
Neural circuits in animals often exhibit oscillatory behavior
Use Simulink to model one behavior of this type:Locomotion
Limbs go Left-right, left-right, left-right
5/25/2018 Mit Matlab Course
202/205
Locomotive behaviors are generated by central patterngenerators, which oscillate on their own naturally
When connected to an appendage, the central patterngenerator will adapt its frequency and move the
appendage. OpenRIOCPGDemo.mdl
Model based on Iwasaki, T., Zheng, M. (2006a). Sensory feedbackmechanism underlying entrainment of central pattern generator to
mechanical resonance. Biological Cybernetics, 94(4), 245-261
Central Pattern Generator Model
Scope forOutput
5/25/2018 Mit Matlab Course
203/205
Limb
Playing with the model
Look at scopesWhat are the output signals?
Delete signalsEspecially the signal after the feedback gain
Change gains
5/25/2018 Mit Matlab Course
204/205
Muscular actuator gainsSwitch feedback gain from negative to positive
Look inside subsystemsWhats inside the CPG?Whats inside the neuron firing dynamics?
Toolboxes
Simulink has many advanced toolboxesControl SystemsNeural NetworksSignal Processing
SimMechanicsVirtual Reality
5/25/2018 Mit Matlab Course
205/205
yReal Time
Hopefully youll get to use some of these powerful tools!
top related