MatLabSlides PDF
MatLabSlides PDF
094
Introduction to Programming in MATLAB
Danilo epanovi
IAP 2010
Course Layout
Lectures
1: Variables, Scripts and Operations
2: Visualization and Programming
3: Solving Equations, Fitting
4: Images, Animations, Advanced Methods
5: Optional: Symbolic Math, Simulink
Course Layout
Prerequisites
Basic familiarity with programming
Basic linear algebra, differential equations, and
probability
Outline
On Athena
add matlab
matlab &
Current directory
Workspace
Command Window
Command History
Click the Make New Folder button, and change the name of the
folder. Do NOT use spaces in folder names. In the MATLAB
folder, make two new folders: IAPMATLAB\day1
help
The most important function for learning MATLAB on
your own
To get info on how to use a function:
help sin
Help lists related functions at the bottom and links to
the doc
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
Outline
Scripts are
collection of commands executed in sequence
written in the MATLAB editor
saved as MATLAB files (.m extension)
Help file
Comments
COMMENT!
Anything following a % is seen as a comment
The first contiguous comment becomes the script's help file
Comment thoroughly to avoid wasting time later
disp('Hello World!');
disp('I am going to learn MATLAB!');
Outline
Variable names
first character must be a LETTER
after that, any combination of letters, numbers and _
CASE SENSITIVE! (var1 is different from Var1)
Command window:
Workspace:
Command window:
Workspace:
1 2
Element by element a=
a= [1 2;3 4]; 3 4
d = [a;b];
e = [d c];
f = [[e e];[a b a]];
str = ['Hello, I am ' 'John'];
Strings are character vectors
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 is saved in the current directory
Default working directory is
\MATLAB
Make sure youre in the desired folder when saving files. Right
now, we should be in:
MATLAB\IAPMATLAB\day1
help clock
start=clock;
size(start)
help datestr
startString=datestr(start);
save startTime start startString
Exercise: Variables
load startTime
disp(['I started learning MATLAB on ' ...
startString]);
Outline
Exponentiation (^)
4^2
(3+4*j)^2
secPerDay=60*60*24;
tau=1.5*secPerDay;
endOfClass=5*secPerDay
knowledgeAtEnd=1-exp(-endOfClass/tau);
disp(['At the end of 6.094, I will know ' ...
num2str(knowledgeAtEnd*100) '% of MATLAB'])
Transpose
For vectors of real numbers .' and ' give same result
Addition and Subtraction
4 1 1 1 1 2 3 1 2 3
2 2 2 .* 1 2 3 = 2 4 6
[1 2 3] .* 2 = ERROR
1 3 3 3 1 2 3 3 6 9
1 4 4 3 3.* 3 3 = 3 3
2 .* 2 = 4
3 1 3
1 2 12 22
3 1.* 3 1 = 3 1 3 4 .^ 2 = 2 2
3 4
Can be any dimension
Operators: standard
4 1 2 1 2 1 2 1 1 1 1 2 3 3 6 9
[1 2 3]* 2 = 11 3 4 ^ 2 = 3 4 * 3 4
2 2 2 * 1 2 3 = 6 12 18
1 Must be square to do powers 3 3 3 1 2 3 9 18 27
1 3* 3 1 = 11 3 3* 3 3 = 3 3
Exercise: Vector Operations
secPerMin=60;
secPerHour=60*secPerMin;
secPerDay=24*secPerHour;
secPerMonth=30.5*secPerDay;
secPerYear=12*secPerMonth;
secondConversion=[secPerYear secPerMonth ...
secPerDay secPerHour secPerMin 1];
currentTime=clock;
elapsedTime=currentTime-start;
t=secondConversion*elapsedTime';
Exercise: Vector Operations
currentKnowledge=1-exp(-t/tau);
disp(['At this time, I know ' ...
num2str(currentKnowledge*100) '% of MATLAB']);
Automatic Initialization
Picking submatrices
A = rand(5) % shorthand for 5x5 matrix
A(1:3,1:2) % specify contiguous submatrix
A([1 5 3], [1 4]) % specify rows and columns
Advanced Indexing 1
12 5
c=
2 13
d=c(1,:); d=[12 5];
e=c(:,2); e=[5;13];
c(2,:)=[3 6]; %replaces second row of c
Advanced Indexing 2
[val,ind]=min(abs(knowledgeVec-0.5));
halfTime=tVec(ind);
disp(['I will know half of MATLAB after ' ...
num2str(halfTime/secPerDay) ' days']);
Outline
Example
x=linspace(0,4*pi,10);
y=sin(x);
1 1
10 x values: 0.8
0.6
1000 x values:
0.8
0.6
0.4 0.4
0.2 0.2
0 0
-0.2 -0.2
-0.4 -0.4
-0.6 -0.6
-0.8 -0.8
-1 -1
0 2 4 6 8 10 12 14 0 2 4 6 8 10 12 14
Exercise: Plotting
figure
plot(tVec/secPerDay, knowledgeVec);
End of Lecture 1
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
6.094
Introduction to programming in MATLAB
Danilo epanovi
IAP 2010
Homework 1 Recap
(1) Functions
(2) Flow Control
(3) Line Plots
(4) Image/Surface Plots
(5) Vectorization
User-defined Functions
Functions look exactly like scripts, but for ONE difference
Functions must have a function declaration
Help file
Function declaration
Outputs Inputs
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7
Functions: Excercise
x=linspace(0,2*pi,f1*16+1);
figure
plot(x,sin(f1*x))
Outline
(1) Functions
(2) Flow Control
(3) Line Plots
(4) Image/Surface Plots
(5) Vectorization
Relational Operators
IF ELSE ELSEIF
if cond if cond if cond1
commands commands1 commands1
end else elseif cond2
commands2 commands2
end else
Conditional statement:
evaluates to true or false commands3
end
for n=1:100
commands
end Command block
WHILE
while cond
commands
end
function plotSin(f1,f2)
x=linspace(0,2*pi,f1*16+1);
figure
if nargin == 1
plot(x,sin(f1*x));
elseif nargin == 2
disp('Two inputs were given');
end
Outline
(1) Functions
(2) Flow Control
(3) Line Plots
(4) Image/Surface Plots
(5) Vectorization
Plot Options
Can change the line color, marker style, and line style by
adding a string argument
plot(x,y,k.-);
to select lines
and delete or
change to see all plot
properties tools at once
to slide the plot
to zoom in/out around
0.2
-0.6
-0.8
-4 -3 -2 -1 0 1 2 3 4
Cartesian Plots
semilogy(y,'r.-'); 40
10
loglog(x,y); 30
10
For example:
20
10
x=0:100; 10
10
semilogy(x,exp(x),'k.-');
0
10
0 10 20 30 40 50 60 70 80 90 100
3D Line Plots
-5
xlim, ylim, zlim
-10
1
0.5 1
0 0.5
0
-0.5 -0.5
-1 -1
Axis Modes
axis square
makes the current axis look like a box
axis tight
fits axes to data
axis equal
makes x and y scales the same
axis xy
puts the origin in the bottom left corner (default for plots)
axis ij
puts the origin in the top left corner (default for
matrices/images)
Multiple Plots in one Figure
.bmp uncompressed
image
.eps high-quality
scaleable format
.pdf compressed
image
0.8
0.8
0.6
0.6
0.4
0.4
0.2
0.2
0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7
Advanced Plotting: Exercise
if nargin == 1
plot(x,sin(f1*x),'rs--',...
'LineWidth',2,'MarkerFaceColor','k');
elseif nargin == 2
subplot(2,1,1);
end
Outline
(1) Functions
(2) Flow Control
(3) Line Plots
(4) Image/Surface Plots
(5) Vectorization
Visualizing matrices
Can set limits for the color axis (analogous to xlim, ylim)
caxis([3000 7000])
Colormaps
You can change the colormap:
imagesc(mat)
default map is jet
colormap(gray)
colormap(cool)
colormap(hot(256))
4 2
3 6
2
1
8
4 2
loop (DUMB)
10
0
6
12
1
8
14 -1
10
0
16
20 -3
16 2 4 6 8 10 12 14 16 18 20
-2
18
20 -3
2 4 6 8 10 12 14 16 18 20
surf
function plotSin(f1,f2)
x=linspace(0,2*pi,round(16*f1)+1);
figure
if nargin == 1
plot(x,sin(f1*x),'rs--',...
'LineWidth',2,'MarkerFaceColor','k');
elseif nargin == 2
y=linspace(0,2*pi,round(16*f2)+1);
[X,Y]=meshgrid(x,y);
Z=sin(f1*X)+sin(f2*Y);
subplot(2,1,1); imagesc(x,y,Z); colorbar;
axis xy; colormap hot
subplot(2,1,2); surf(X,Y,Z);
end
Exercise: 3-D Plots
plotSin(3,4) generates this figure
2
6
5
1
4
3 0
2
-1
1
0 -2
0 1 2 3 4 5 6
2
0
-2
8
6 7
6
4 5
4
2 3
2
1
0 0
Specialized Plotting Functions
(1) Functions
(2) Flow Control
(3) Line Plots
(4) Image/Surface Plots
(5) Vectorization
Revisiting find
Avoid loops!
Built-in functions will make it faster to write and execute
Efficient Code
Avoid loops
This is referred to as vectorization
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
For example, to sum up every two consecutive terms:
a=rand(1,100); a=rand(1,100);
b=zeros(1,100); b=[0 a(1:end-1)]+a;
for n=1:100 Efficient and clean.
Can also do this using
if n==1 conv
b(n)=a(n);
else
b(n)=a(n-1)+a(n);
end
end
Slow and complicated
End of Lecture 2
(1) Functions
(2) Flow Control
(3) Line Plots
(4) Image/Surface Plots
(5) Vectorization
Vectorization makes
coding fun!
MIT OpenCourseWare
http://ocw.mit.edu
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
6.094
Introduction to programming in MATLAB
Danilo epanovi
IAP 2008
Homework 2 Recap
Given a matrix
mat=[1 2 -3;-3 -1 1;1 -1 1];
System 1:
x + 4 y = 34
3 x + y = 2
System 2:
2x 2 y = 4
x + y = 3
3x + 4 y = 2
Exercise: Linear Algebra
Plot the fitted polynomial on the same plot, using the same
x values and a red line
Exercise: Polynomial Fitting
2
Evaluate y = x for x=-4:0.1:4.
x=-4:0.1:4;
y=x.^2;
x=fminbnd(@(x) (cos(exp(x))+x^2-1),-1,2);
Optimization Toolbox
0.4
y=sin(x); 0.2
dydx=diff(y)./diff(x); 0
-0.4
-0.6
dm=diff(mat,1,2)
first difference of mat along the 2nd dimension, dm=[2 2;4 -2]
see help for more details
The opposite of diff is the cumulative sum cumsum
2D gradient
[dx,dy]=gradient(mat);
Numerical Integration
Using the correct ODE solver can save you lots of time and
give more accurate results
ode23
Low-order solver. Use when integrating over small intervals
or when accuracy is less important than speed
ode45
High order (Runge-Kutta) solver. High accuracy and
reasonable speed. Most commonly used.
ode15s
Stiff ODE solver (Gear's algorithm), use when the diff eq's
have time constants that vary by orders of magnitude
ODE Solvers: Standard Syntax
ODE file:
y has [A;B]
dydt has
[dA/dt;dB/dt]
Chem reaction
1
A
0.9 B
0.8
0.7
Amount of chemical (g)
0.6
0.5
0.4
0.3
0.2
0.1
0
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5
Time (s)
Higher Order Equations
Must make into a system of first-order equations to use
ODE solvers
Nonlinear is OK!
Pendulum example:
g
&& + sin ( ) = 0
L
g
&& = sin ( )
L
let & =
g
& = sin ( )
L
v
x=
v
dx &
=
dt &
Courtesy of The MathWorks, Inc. Used with permission.
Plotting the Output
angle (rad) 2
-2
-4
-6
-8
0 1 2 3 4 5 6 7 8 9 10
Plotting the Output
4
Velocity is greatest
2 when theta=0
Velocity
-2
Velocity=0 when -4
-8
-3 -2 -1 0 1 2 3
Position
ODE Solvers: Custom Options
6
y(t)
0
0 1 2 3 4 5 6 7 8 9 10
Time
End of Lecture 3
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
6.094
Introduction to programming in MATLAB
Danilo epanovi
IAP 2010
Homework 3 Recap
Common issues:
The ODE file should be separate from the command that
solves it. ie. you should not be calling ode45 from within
your ODE file
The structure of the output of an ode solver is to have time
running down the columns, so each column of y is a
variable, and the last row of y are the last values
Built-in functions
mean, median, mode
350
y=randn(1,1000)
300
250
200
y2=y*5+8 150
100
0
-25 -20 -15 -10 -5 0 5 10 15 20 25
90
80
70
60
50
40
30
20
10
0
-25 -20 -15 -10 -5 0 5 10 15 20 25
Exercise: Probability
We will simulate Brownian motion in 1 dimension. Call the script
brown
Make a 10,000 element vector of zeros
Write a loop to keep track of the particles position at each time
Start at 0. To get the new position, pick a random number, and if
its <0.5, go left; if its >0.5, go right. Store each new position in
the 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 script
brown
Make a 10,000 element vector of zeros
Write a loop to keep track of the particles position at each time
Start at 0. To get the new position, pick a random number, and if
its <0.5, go left; if its >0.5, go right. Store each new position in
the kth position in the vector
Plot a 50 bin histogram of the positions.
x=zeros(10000,1);
for n=2:10000
if rand<0.5
x(n)=x(n-1)-1;
else
x(n)=x(n-1)+1;
end
end
figure;
hist(x,50);
Outline
L e o []
One cell can contain people's names, ages, and the ages of
their children
To do the same with matrices, you would need 3 variables
and padding
Cells: initialization
To add fields
s.name = 'Jack Bauer';
s.scores = [95 98 67];
s.year = 'G3';
Fields can be anything: matrix, cell, even struct
Useful for keeping variables together
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
Avi
good when you have natural frames with lots of colors and
few clearly defined edges
Animated gif
Good for making movies of plots or text where only a few
colors exist (limited to 256) and there are well-defined
lines
Making Animations
temp=ceil(rand(300,300,1,10)*256);
imwrite(temp,jet(256),'testGif.gif',...
'delaytime',0.1,'loopcount',100);
Step to next
Two breakpoints
http://www.mathworks.com/matlabcentral/
End of Lecture 4
THE END
MIT OpenCourseWare
http://ocw.mit.edu
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
6.094
Introduction to Programming in MATLAB
Instructor:
Danilo epanovi
IAP 2010
Outline
Advantages Disadvantages
Or use syms
syms x y real
shorthand for x=sym('x','real'); y=sym('y','real');
Symbolic Expressions
expand((a-c)^2);
multiplies out
factor(ans)
factors the expression
matInv=inv(mat)
Computes inverse symbolically
Cleaning up Symbolic Statements
pretty(ans)
makes it look nicer
collect(3*x+4*y-1/3*x^2-x+3/2*y)
collects terms
simplify(cos(x)^2+sin(x)^2)
simplifies expressions
subs(c^2,c,5) ans=
25
Replaces variables with numbers
or expressions. To do multiple substitutions
pass a cell of variable names followed by a cell of values
subs(c^2,c,x/7) ans=
1/49*x^2
More Symbolic Operations
syms a b r x y
solve('(x-a)^2+(y-b)^2=r^2','x')
solve('(x-a)^2+(y-b)^2=r^2','y')
Create a new
Simulink file,
similar to how
you make a new
script
Input
Low pass
High Pass
Math
Takes the signal and performs a math operation
Add, subtract, round, multiply, gain, angle
Continuous
Adds differential equations to the system
Integrals, Derivatives, Transfer Functions,
State Space
Discontinuities
Adds nonlinearities to your system
Discrete
Simulates discrete difference equations
Useful for digital systems
Building systems
Sources
Step input, white noise, custom input, sine
wave, ramp input,
Provides input to your system
Sinks
Scope: Outputs to plot
simout: Outputs to a MATLAB vector on workspace
MATLAB mat file
Outline
x=a.data;
names=a.colheaders;
Importing Data
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.