6.
094
Introduction to Programming in MATLAB
Lecture 1: Variables, Scripts,
and Operations
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
Problem Sets / Office Hours
One per day, should take about 3 hours to do
Submit doc or pdf (include code, figures)
No set office hours but available by email
Requirements for passing
Attend all lectures
Complete all problem sets (-, , +)
Prerequisites
Basic familiarity with programming
Basic linear algebra, differential equations, and
probability
Outline
(1) Getting Started
(2) Scripts
(3) Making Variables
(4) Manipulating Variables
(5) Basic Plotting
Getting Started
To get MATLAB Student Version for yourself
https://msca.mit.edu/cgi-bin/matlab
Use VPN client to enable off-campus access
Note: MIT certificates are required
Open up MATLAB for Windows
Through the START Menu
On Athena
add matlab
matlab &
Current directory
Workspace
Command Window
Command History
Courtesy of The MathWorks, Inc. Used with permission.
Making Folders
Use folders to keep your programs organized
To make a new folder, click the Browse button next to Current
Directory
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
Highlight the folder you just made and click OK
The current directory is now the folder you just created
To see programs outside the current directory, they should be in
the Path. Use File-> Set Path to add folders to the path
Customization
File Preferences
Allows you personalize your MATLAB experience
Courtesy of The MathWorks, Inc. Used with permission.
MATLAB Basics
MATLAB can be thought of as a super-powerful
graphing 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 Java
Commands executed line by line
Help/Docs
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
(1) Getting Started
(2) Scripts
(3) Making Variables
(4) Manipulating Variables
(5) Basic Plotting
Scripts: Overview
Scripts are
collection of commands executed in sequence
written in the MATLAB editor
saved as MATLAB files (.m extension)
To create an MATLAB file from command-line
edit helloWorld.m
or click
Courtesy of The MathWorks, Inc. Used with permission.
Scripts: the Editor
* Means that it's not saved
Line numbers
MATLAB file Real-time
path Debugging tools error check
Help file
Comments
Possible breakpoints Courtesy of The MathWorks, Inc. Used with permission.
Scripts: Some Notes
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
Note that scripts are somewhat static, since there is no
input and no explicit output
All variables created and modified in a script exist in the
workspace even after it has stopped running
Exercise: Scripts
Make a helloWorld script
When run, the script should display the following text:
Hello World!
I am going to learn MATLAB!
Hint: use disp to display strings. Strings are written
between single quotes, like 'This is a string'
Exercise: Scripts
Make a helloWorld script
When run, the script should display the following text:
Hello World!
I am going to learn MATLAB!
Hint: use disp to display strings. Strings are written
between single quotes, like 'This is a string'
Open the editor and save a script as helloWorld.m. This is
an easy script, containing two lines of code:
% helloWorld.m
% my first hello world program in MATLAB
disp('Hello World!');
disp('I am going to learn MATLAB!');
Outline
(1) Getting Started
(2) Scripts
(3) Making Variables
(4) Manipulating Variables
(5) Basic Plotting
Variable Types
MATLAB is a weakly typed language
No 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 vectors or matrices of
doubles or chars
Other types are also supported: complex, symbolic, 16-bit
and 8 bit integers, etc. You will be exposed to all these
types through the homework
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 from Var1)
Built-in variables. Dont use these names!
i and j can be used to indicate complex numbers
pi 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
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;
Arrays
Like other programming languages, arrays are an
important 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!
Row Vectors
Row vector: comma or space separated values between
brackets
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.
Column Vectors
Column vector: semicolon separated values between
brackets
column = [4;2;7;4]
Command window:
Workspace:
Courtesy of The MathWorks, Inc. Used with permission.
size & length
You can tell the difference between a row and a column
vector by:
Looking in the workspace
Displaying the variable in the command window
Using the size function
To get a vector's length, use the length function
Matrices
Make matrices like vectors
1 2
Element by element a=
a= [1 2;3 4]; 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]];
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
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;
Exercise: Variables
Get and save the current date and time
Create a variable start using the function clock
What is the size of start? Is it a row or column?
What does start contain? See help clock
Convert the vector start to a string. Use the function
datestr and name the new variable startString
Save start and startString into a mat file named
startTime
Exercise: Variables
Get and save the current date and time
Create a variable start using the function clock
What is the size of start? Is it a row or column?
What does start contain? See help clock
Convert the vector start to a string. Use the function
datestr and name the new variable startString
Save start and startString into a mat file named
startTime
help clock
start=clock;
size(start)
help datestr
startString=datestr(start);
save startTime start startString
Exercise: Variables
Read in and display the current date and time
In helloWorld.m, read in the variables you just saved using
load
Display the following text:
I started learning MATLAB on *start date and time*
Hint: use the disp command again, and remember that
strings are just vectors of characters so you can join two
strings by making a row vector with the two strings as sub-
vectors.
Exercise: Variables
Read in and display the current date and time
In helloWorld.m, read in the variables you just saved using
load
Display the following text:
I started learning MATLAB on *start date and time*
Hint: use the disp command again, and remember that
strings are just vectors of characters so you can join two
strings by making a row vector with the two strings as sub-
vectors.
load startTime
disp(['I started learning MATLAB on ' ...
startString]);
Outline
(1) Getting Started
(2) Scripts
(3) Making Variables
(4) Manipulating Variables
(5) Basic Plotting
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 command window
clc
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);
Exercise: Scalars
You will learn MATLAB at an exponential rate! Add the
following to your helloWorld script:
Your learning time constant is 1.5 days. Calculate the number of
seconds in 1.5 days and name this variable tau
This class lasts 5 days. Calculate the number of seconds in 5 days
and name this variable endOfClass
This equation describes your knowledge as a function of time t:
t /
k = 1 e
How well will you know MATLAB at endOfClass? Name this
variable knowledgeAtEnd. (use exp)
Using the value of knowledgeAtEnd, display the phrase:
At the end of 6.094, I will know X% of MATLAB
Hint: to convert a number to a string, use num2str
Exercise: Scalars
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
The transpose operators turns a column vector into a row
vector and vice versa
a = [1 2 3 4+i]
transpose(a)
a'
a.'
The ' gives the Hermitian-transpose, i.e. transposes and
conjugates all complex numbers
For vectors of real numbers .' and ' give same result
Addition and Subtraction
Addition and subtraction are element-wise; sizes must
match (unless one is a scalar):
[12 3 32 11] 12 3 9
1 1 2
+ [ 2 11 30 32] =
10 13 23
= [14 14 2 21]
0 33
33
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);
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 handles
vectors elementwise
Operators (* / ^) have two modes of operation
element-wise
standard
Operators: element-wise
To do element-wise operations, use the dot: . (.*, ./, .^).
BOTH dimensions 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 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
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 (^) 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 this
later)
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
Calculate how many seconds elapsed since the start of
class
In helloWorld.m, make variables called secPerMin,
secPerHour, secPerDay, secPerMonth (assume 30.5 days
per month), and secPerYear (12 months in year), which
have the number of seconds in each time period.
Assemble a row vector called secondConversion that has
elements in this order: secPerYear, secPerMonth,
secPerDay, secPerHour, secPerMinute, 1.
Make a currentTime vector by using clock
Compute elapsedTime by subtracting currentTime from
start
Compute t (the elapsed time in seconds) by taking the dot
product of secondConversion and elapsedTime (transpose
one of them to get the dimensions right)
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
Display the current state of your knowledge
Calculate currentKnowledge using the same relationship as
before, and the t we just calculated:
t /
k = 1 e
Display the following text:
At this time, I know X% of MATLAB
Exercise: Vector Operations
Display the current state of your knowledge
Calculate currentKnowledge using the same relationship as
before, and the t we just calculated:
t /
k = 1 e
Display the following text:
At this time, I know X% of MATLAB
currentKnowledge=1-exp(-t/tau);
disp(['At this time, I know ' ...
num2str(currentKnowledge*100) '% of MATLAB']);
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 uninitialized
variables)
The general function call is:
var=zeros(M,N);
Number of rows Number of columns
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, but see help
Exercise: Vector Functions
Calculate your learning trajectory
In helloWorld.m, make a linear time vector tVec that has
10,000 samples between 0 and endOfClass
Calculate the value of your knowledge (call it
knowledgeVec) at each of these time points using the same
equation as before:
t /
k = 1 e
Exercise: Vector Functions
Calculate your learning trajectory
In helloWorld.m, make a linear time vector tVec that has
10,000 samples between 0 and endOfClass
Calculate the value of your knowledge (call it
knowledgeVec) at each of these time points using the same
equation as before:
t /
k = 1 e
tVec = linspace(0,endOfClass,10000);
knowledgeVec=1-exp(-tVec/tau);
Vector Indexing
MATLAB indexing starts with 1, not 0
We will not respond to any emails where this is the
problem.
a(n) returns the nth element
a = [13 5 9 10]
a(1) a(2) a(3) a(4)
The index argument can be a vector. In this case, each
element is looked up individually, and returned as a vector
of 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];
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
b(1,1) 14 33 b(1,2) b(1) 14 33 b(3)
b(2,1)
9 8 b(2,2) b(2)
9 8 b(4)
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
To select rows or columns of a matrix, use the :
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
MATLAB contains functions to help you find desired values
within a vector or matrix
vec = [5 3 1 9 7]
To get the minimum value and its index:
[minVal,minInd] = min(vec);
max works the same way
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: Indexing
When will you know 50% of MATLAB?
First, find the index where knowledgeVec is closest to 0.5.
Mathematically, what you want is the index where the value
of knowledgeVec 0.5 is at a minimum (use abs and min).
Next, use that index to look up the corresponding time in
tVec and name this time halfTime.
Finally, display the string: I will know half of MATLAB after X days
Convert halfTime to days by using secPerDay
Exercise: Indexing
When will you know 50% of MATLAB?
First, find the index where knowledgeVec is closest to 0.5.
Mathematically, what you want is the index where the value
of knowledgeVec 0.5 is at a minimum (use abs and min).
Next, use that index to look up the corresponding time in
tVec and name this time halfTime.
Finally, display the string: I will know half of MATLAB after X days
Convert halfTime to days by using secPerDay
[val,ind]=min(abs(knowledgeVec-0.5));
halfTime=tVec(ind);
disp(['I will know half of MATLAB after ' ...
num2str(halfTime/secPerDay) ' days']);
Outline
(1) Getting Started
(2) Scripts
(3) Making Variables
(4) Manipulating Variables
(5) Basic Plotting
Did everyone sign in?
Plotting
Example
x=linspace(0,4*pi,10);
y=sin(x);
Plot values against their index
plot(y);
Usually we want to plot y versus x
plot(x,y);
MATLAB makes visualizing data
fun and easy!
What does plot do?
plot generates dots at each (x,y) pair and then connects the dots
with 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 error
plot([1 2], [1 2 3])
error!!
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
Plot the learning trajectory
In helloWorld.m, open a new figure (use figure)
Plot the knowledge trajectory using tVec and
knowledgeVec. When plotting, convert tVec to days by
using secPerDay
Zoom in on the plot to verify that halfTime was calculated
correctly
Exercise: Plotting
Plot the learning trajectory
In helloWorld.m, open a new figure (use figure)
Plot the knowledge trajectory using tVec and
knowledgeVec. When plotting, convert tVec to days by
using secPerDay
Zoom in on the plot to verify that halfTime was calculated
correctly
figure
plot(tVec/secPerDay, knowledgeVec);
End of Lecture 1
(1) Getting Started
(2) Scripts
(3) Making Variables
(4) Manipulating Variables
(5) Basic Plotting
Hope that wasnt too much!!
MIT OpenCourseWare
http://ocw.mit.edu
6.094 Introduction to MATLAB
January (IAP) 2010
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
6.094
Introduction to programming in MATLAB
Lecture 2: Visualization and Programming
Danilo epanovi
IAP 2010
Homework 1 Recap
How long did it take to do required problems?
Did anyone do optional problems?
Was level of guidance appropriate?
Unanswered Questions?
Some things that came up:
Use of semicolon never required if one command per line.
You can also put multiple commands on one line; in this
case a semicolon is necessary to separate commands:
x=1:10; y=(x-5).^2; plot(x,y);
Assignment using indices remember that you can index
into matrices to either look up values or to assign value:
x=rand(50,1); inds=find(x<0.1); y=x(inds);
x(inds)=-x(inds); x(inds)=3;
Outline
(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
Courtesy of The MathWorks, Inc. Used with permission.
User-defined Functions
Some comments about the function declaration
Inputs must be specified
function [x, y, z] = funName(in1, in2)
Must have the reserved Function name should
word: function match MATLAB file
name
If more than one output,
must be in brackets
No need for return: MATLAB 'returns' the variables whose
names match those in the function declaration
Variable scope: Any variables created within the function
but not returned disappear after the function stops running
Functions: overloading
We're familiar with
zeros
size
length
sum
Look at the help file for size by typing
help size
The help file describes several ways to invoke the function
D = SIZE(X)
[M,N] = SIZE(X)
[M1,M2,M3,...,MN] = SIZE(X)
M = SIZE(X,DIM)
Functions: overloading
MATLAB functions are generally overloaded
Can take a variable number of inputs
Can return a variable number of outputs
What would the following commands return:
a=zeros(2,4,8); %n-dimensional matrices are OK
D=size(a)
[m,n]=size(a)
[x,y,z]=size(a)
m2=size(a,2)
You can overload your own functions by having variable
input and output arguments (see varargin, nargin,
varargout, nargout)
Functions: Excercise
Write a function with the following declaration:
function plotSin(f1)
In the function, plot a sin wave with frequency f1, on the
range [0,2]: sin ( f1 x )
To get good sampling, use 16 points per period.
1
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
Write a function with the following declaration:
function plotSin(f1)
In the function, plot a sin wave with frequency f1, on the
range [0,2]: sin ( f1 x )
To get good sampling, use 16 points per period.
In an MATLAB file saved as plotSin.m, write the following:
function plotSin(f1)
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
MATLAB uses mostly standard relational operators
equal ==
not equal ~=
greater than >
less than <
greater or equal >=
less or equal <=
Logical operators elementwise short-circuit (scalars)
And & &&
Or | ||
Not ~
Xor xor
All true all
Any true any
Boolean values: zero is false, nonzero is true
See help . for a detailed list of operators
if/else/elseif
Basic flow-control, common to all languages
MATLAB syntax is somewhat unique
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
No need for parentheses: command blocks are between
reserved words
for
for loops: use for a known number of iterations
MATLAB syntax:
Loop variable
for n=1:100
commands
end Command block
The loop variable
Is defined as a vector
Is a scalar within the command block
Does not have to have consecutive values (but it's usually
cleaner if they're consecutive)
The command block
Anything between the for line and the end
while
The while is like a more general for loop:
Don't need to know number of iterations
WHILE
while cond
commands
end
The command block will execute while the conditional
expression is true
Beware of infinite loops!
Exercise: Conditionals
Modify your plotSin(f1) function to take two inputs: plotSin(f1,f2)
If the number of input arguments is 1, execute the plot command
you wrote before. Otherwise, display the line 'Two inputs were
given'
Hint: the number of input arguments are in the built-in variable
nargin
Exercise: Conditionals
Modify your plotSin(f1) function to take two inputs:
plotSin(f1,f2)
If the number of input arguments is 1, execute the plot command
you wrote before. Otherwise, display the line 'Two inputs were
given'
Hint: the number of input arguments are in the built-in variable
nargin
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.-);
color marker line-style
Can plot without connecting the dots by omitting line style
argument
plot(x,y,.)
Look at help plot for a full list of colors, markers, and
linestyles
Playing with the Plot
to select lines
and delete or
change to see all plot
properties tools at once
to slide the plot
to zoom in/out around
Courtesy of The MathWorks, Inc. Used with permission.
Line and Marker Options
Everything on a line can be customized
plot(x,y,'--s','LineWidth',2,...
'Color', [1 0 0], ...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g',...
'MarkerSize',10)
You can set colors by using
a vector of [R G B] values 0.8
or a predefined color 0.6
character like 'g', 'k', etc. 0.4
0.2
See doc line_props for a full list of-0.2
properties that can be specified
-0.4
-0.6
-0.8
-4 -3 -2 -1 0 1 2 3 4
Cartesian Plots
We have already seen the plot function
x=-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');
50
10
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
We can plot in 3 dimensions just as easily as in 2
time=0:0.001:4*pi;
x=sin(time);
y=cos(time);
z=time;
plot3(x,y,z,'k','LineWidth',2);
zlabel('Time');
10
Use tools on figure to rotate it 5
Can set limits on all 3 axes 0
-5
xlim, ylim, zlim
-10
1
0.5 1
0 0.5
0
-0.5 -0.5
-1 -1
Axis Modes
Built-in 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
To have multiple axes in one figure
subplot(2,3,1)
makes a figure with 2 rows and three columns of axes, and
activates the first axis for plotting
each axis can have labels, a legend, and a title
subplot(2,3,4:6)
activating a range of axes fuses them into one
To close existing figures
close([1 3])
closes figures 1 and 3
close all
closes all figures (useful in scripts/functions)
Copy/Paste Figures
Figures can be pasted into other apps (word, ppt, etc)
Edit copy options figure copy template
Change 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
Figures can be saved in many formats. The common ones
are:
.fig preserves all
information
.bmp uncompressed
image
.eps high-quality
scaleable format
.pdf compressed
image
Courtesy of The MathWorks, Inc. Used with permission.
Advanced Plotting: Exercise
Modify the plot command in your plotSin function to use
squares as markers and a dashed red line of thickness 2
as the line. Set the marker face color to be black
(properties are LineWidth, MarkerFaceColor)
If there are 2 inputs, open a new figure with 2 axes, one on
top of the other (not side by side), and activate the top one
(subplot)
plotSin(6) plotSin(1,2)
1 1
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
Modify the plot command in your plotSin function to use
squares as markers and a dashed red line of thickness 2
as the line. Set the marker face color to be black
(properties are LineWidth, MarkerFaceColor)
If there are 2 inputs, open a new figure with 2 axes, one on
top of the other (not side by side), and activate the top one
(subplot)
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
Any matrix can be visualized as an image
mat=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
You can change the colormap:
imagesc(mat)
default map is jet
colormap(gray)
colormap(cool)
colormap(hot(256))
See help hot for a list
Can define custom colormap
map=zeros(256,3);
map(:,2)=(0:255)/255;
colormap(map);
Surface Plots
It is more common to visualize surfaces in 3D
Example: f ( x, y ) = sin ( x ) cos ( y )
x [ , ] ; y [ , ]
surf puts 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
3
How can we make these matrices
2
4 2
3 6
2
1
8
4 2
loop (DUMB)
10
0
6
12
1
8
14 -1
10
0
16
built-in function: meshgrid
12 -2
18
14 -1
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
Make the x and y vectors
x=-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 matrices
Z =sin(X).*cos(Y);
Plot the surface
surf(X,Y,Z)
surf(x,y,Z);
surf Options
See help surf for more options
There are three types of surface shading
shading faceted
shading flat
shading interp
You can change colormaps
colormap(gray)
contour
You can make surfaces two-dimensional by using contour
contour(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
Modify plotSin to do the following:
If two inputs are given, evaluate the following function:
Z = sin ( f1 x ) + sin ( f 2 y )
y should be just like x, but using f2. (use meshgrid to get
the X and Y matrices)
In the top axis of your subplot, display an image of the Z
matrix. Display the colorbar and use a hot colormap. Set
the axis to xy (imagesc, colormap, colorbar, axis)
In the bottom axis of the subplot, plot the 3-D surface of Z
(surf)
Exercise: 3-D Plots
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
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 graphs
bar(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 functions
stairs(1:10,rand(1,10));
fill-draws and fills a polygon with specified vertices
fill([0 1 0.5],[0 0 1],'r');
see help on these functions for syntax
doc specgraph for a complete list
Outline
(1) Functions
(2) Flow Control
(3) Line Plots
(4) Image/Surface Plots
(5) Vectorization
Revisiting find
find is a very important function
Returns indices of nonzero values
Can simplify code and help avoid loops
Basic syntax: index=find(cond)
x=rand(1,100);
inds = find(x>0.4 & x<0.6);
inds will contain the indices at which x has values between
0.4 and 0.6. This is what happens:
x>0.4 returns a vector with 1 where true and 0 where false
x<0.6 returns a similar vector
The & combines the two vectors using an and
The find returns the indices of the 1's
Example: Avoiding Loops
Given x= sin(linspace(0,10*pi,100)), how many of the
entries are positive?
Using a loop and if/else Being more clever
count=0; count=length(find(x>0));
for n=1:length(x)
length(x) Loop time Find time
if x(n)>0
100 0.01 0
count=count+1;
10,000 0.1 0
end
100,000 0.22 0
end
1,000,000 1.5 0.04
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
6.094 Introduction to MATLAB
January (IAP) 2010
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
6.094
Introduction to programming in MATLAB
Lecture 3 : Solving Equations and Curve Fitting
Danilo epanovi
IAP 2008
Homework 2 Recap
How long did it take?
Using min with matrices:
a=[3 7 5;1 9 10; 30 -1 2];
b=min(a); % returns the min of each column
m=min(b); % returns min of entire a matrix
m=min(min(a)); % same as above
m=min(a(:)); % makes a a vector, then gets min
Common mistake:
[m,n]=find(min(a)); % think about what happens
How to make and run a function: save the file, then call it
from the command window like any other function. No need
to 'compile' or make it official in any other way
Outline
(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 linear
x+2y-3z=5
algebra fun!
-3x-y+z=-8
x-y+z=0
Construct matrices so the system is described by Ax=b
A=[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. Solution
depends on whether the system is over or underdetermined.
More Linear Algebra
Given a matrix
mat=[1 2 -3;-3 -1 1;1 -1 1];
Calculate the rank of a matrix
r=rank(mat);
the number of linearly independent rows or columns
Calculate the determinant
d=det(mat);
mat must be square
if determinant is nonzero, matrix is invertible
Get the matrix inverse
E=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
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:
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
Solve the following systems of equations:
System 1: A=[1 4;-3 1];
x + 4 y = 34 b=[34;2];
3 x + y = 2 rank(A)
x=inv(A)*b;
System 2: A=[2 -2;-1 1;3 4];
2x 2 y = 4 b=[4;3;2];
rank(A)
x + y = 3
rectangular matrix
3x + 4 y = 2 x1=A\b;
gives least squares solution
error=abs(A*x1-b)
Outline
(1) Linear Algebra
(2) Polynomials
(3) Optimization
(4) Differentiation/Integration
(5) Differential Equations
Polynomials
Many functions can be well described by a high-order
polynomial
MATLAB represents a polynomials by a vector of coefficients
if vector P describes a polynomial
ax3+bx2+cx+d
P(1) P(2) P(3) P(4)
P=[1 0 -2] represents the polynomial x2-2
P=[2 0 0 0] represents the polynomial 2x3
Polynomial Operations
P is a vector of length N+1 describing an N-th order polynomial
To get the roots of a polynomial
r=roots(P)
r is a vector of length N
Can also get the polynomial from the roots
P=poly(r)
r is a vector length N
To evaluate a polynomial at a point
y0=polyval(P,x0)
x0 is a single value; y0 is a single value
To evaluate a polynomial at many points
y=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
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 = -3:.01:3;
plot(x,polyval(p2,x), r--);
Exercise: Polynomial Fitting
Evaluate y = x2 for x=-4:0.1:4.
Add random noise to these samples. Use randn. Plot the
noisy signal with . markers
Fit a 2nd degree polynomial to the noisy data
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;
Add random noise to these samples. Use randn. Plot the
noisy signal with . markers
y=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 same
x values and a red line
hold on;
plot(x,polyval(p,x),r)
Outline
(1) Linear Algebra
(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
fzero needs a function passed to it.
We will see this more and more as we delve into solving
equations.
Make a separate function file
x=fzero('myfun',1)
x=fzero(@myfun,1)
1 specifies a
point close to where
you think the root is
Courtesy of The MathWorks, Inc. Used with permission.
Minimizing a Function
fminbnd: minimizing a function over a bounded interval
x=fminbnd('myfun',-1,2);
myfun takes a scalar input and returns a scalar output
myfun(x) will be the minimum of myfun for -1x 2
fminsearch: unconstrained interval
x=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
x=fzero(@myfun,1)
What if myfun is really simple?
Instead, you can make an anonymous function
x=fzero(@(x)(cos(exp(x))+x^2-1), 1 );
input function to evaluate
x=fminbnd(@(x) (cos(exp(x))+x^2-1),-1,2);
Optimization Toolbox
If you are familiar with optimization methods, use the
optimization toolbox
Useful for larger, more structured optimization problems
Sample functions (see help for more info)
linprog
linear programming using interior point methods
quadprog
quadratic programming solver
fmincon
constrained nonlinear optimization
Exercise: Min-Finding
Find the minimum of the function f ( x ) = cos ( 4 x ) sin (10 x ) e
x
over the range to . Use fminbnd.
Plot the function on this range to check that this is the
minimum.
Exercise: Min-Finding
Find the minimum of the function f ( x ) = cos ( 4 x ) sin (10 x ) e
x
over the range to . Use fminbnd.
Plot the function on this range to check that this is the
minimum.
Make the following function:
function y=myFun(x)
y=cos(4*x).*sin(10*x).*exp(-abs(x));
Find the minimum in the command window:
x0=fminbnd('myFun',-pi,pi);
Plot to check if it's right
figure; x=-pi:.01:pi; plot(x,myFun(x));
Outline
(1) Linear Algebra
(2) Polynomials
(3) Optimization
(4) Differentiation/Integration
(5) Differential Equations
Numerical Differentiation
1
MATLAB can 'differentiate' numerically0.8
x=0:0.01:2*pi; 0.6
0.4
y=sin(x); 0.2
dydx=diff(y)./diff(x); 0
diff computes the first difference -0.2
-0.4
-0.6
Can also operate on matrices -0.8
mat=[1 3 5;4 8 6]; -1
0 100 200 300 400 500 600 700
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
MATLAB contains common integration methods
Adaptive Simpson's quadrature (input is a function)
q=quad('myFun',0,10);
q is the integral of the function myFun from 0 to 10
q2=quad(@(x) sin(x)*x,0,pi)
q2 is the integral of sin(x)*x 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 pi
z2=trapz(x,sqrt(exp(x))./x)
x
z2 is the integral of e x from 0 to pi
Outline
(1) Linear Algebra
(2) Polynomials
(3) Optimization
(4) Differentiation/Integration
(5) Differential Equations
ODE Solvers: Method
Given a differential equation, the solution can be found by
integration:
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
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
To use standard options and variable time step
[t,y]=ode45('myODE',[0,10],[1;0])
ODE integrator: Initial conditions
23, 45, 15s Time range
ODE function
Inputs:
ODE function name (or anonymous function). This function
takes 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
variables.
ODE Function
The ODE function must return the value of the derivative at
a given time and function value
Example: chemical reaction
10
Two equations
dA A B
= 10 A + 50 B
dt 50
dB
= 10 A 50 B
dt
ODE file:
y has [A;B]
dydt has
[dA/dt;dB/dt]
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]);
assumes that only chemical B exists initially
plot(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
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
We can solve for the position and velocity of the pendulum:
[t,x]=ode45('pendulum',[0 10],[0.9*pi 0]);
assume pendulum is almost horizontal
plot(t,x(:,1));
hold on;
plot(t,x(:,2),'r');
legend('Position','Velocity');
8
Position
Velocity
6
Velocity (m/s)
Position in terms of 4
angle (rad) 2
-2
-4
-6
-8
0 1 2 3 4 5 6 7 8 9 10
Plotting the Output
Or we can plot in the phase plane:
plot(x(:,1),x(:,2));
xlabel('Position');
yLabel('Velocity');
The phase plane is just a plot of one variable versus the
other: 8
4
Velocity is greatest
2 when theta=0
Velocity
-2
Velocity=0 when -4
theta is the greatest -6
-8
-3 -2 -1 0 1 2 3
Position
ODE Solvers: Custom Options
MATLAB's ODE solvers use a variable timestep
Sometimes a fixed timestep is desirable
[t,y]=ode45('chem',[0:0.001:0.5],[0 1]);
Specify the timestep by giving a vector of times
The function value will be returned at the specified points
Fixed timestep is usually slower because function values
are interpolated to give values at the desired timepoints
You can customize the error tolerances using odeset
options=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 than
RelTol 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 for y ( t ) on the range t=[0 10], with
initial condition y ( 0 ) = 10 and dy dt = t y 10
Plot the result.
Exercise: ODE
Use ode45 to solve for y ( t ) on the range t=[0 10], with
initial condition y ( 0 ) = 10 and dy dt = t y 10
Plot the result.
Make the following function
function dydt=odefun(t,y)
dydt=-t*y/10;
Integrate the ODE function and plot the result
[t,y]=ode45(odefun,[0 10],10);
Alternatively, use an anonymous function
[t,y]=ode45(@(t,y) t*y/10,[0 10],10);
Plot the result
plot(t,y);xlabel('Time');ylabel('y(t)');
Exercise: ODE
The integrated function looks like this:
Function y(t), integrated by ode45
10
6
y(t)
0
0 1 2 3 4 5 6 7 8 9 10
Time
End of Lecture 3
(1) Linear Algebra
(2) Polynomials
(3) Optimization
(4) Differentiation/Integration
(5) Differential Equations
We're almost done!
MIT OpenCourseWare
http://ocw.mit.edu
6.094 Introduction to MATLAB
January (IAP) 2010
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
6.094
Introduction to programming in MATLAB
Lecture 4: Advanced Methods
Danilo epanovi
IAP 2010
Homework 3 Recap
How long did it take?
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
HW 4 was updated today, so download it again if you
already started. Show a juliaAnimation
Today is the last required class: make sure the sign-in
sheet is accurate regarding your credit/listener status
Outline
(1) Probability and Statistics
(2) Data Structures
(3) Images and Animation
(4) Debugging
(5) Online Resources
Statistics
Whenever analyzing data, you have to compute statistics
scores = 100*rand(1,100);
Built-in functions
mean, 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 specified
bin edges 0 to <10, 10 to <2090 to <100. you can plot
these manually:
bar(0:10:100,N,'r')
Random Numbers
Many probabilistic processes rely on random numbers
MATLAB contains the common distributions built in
rand
draws from the uniform distribution from 0 to 1
randn
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 generators
rand('state',0); rand(1); rand(1);
rand('state',0); rand(1);
Changing Mean and Variance
We can alter the given distributions
y=rand(1,100)*10+5;
gives 100 uniformly distributed numbers between 5 and 15
y=floor(rand(1,100)*10+6);
gives 100 uniformly distributed integers between 10 and
15. floor or ceil is better to use here than round
400
350
y=randn(1,1000)
300
250
200
y2=y*5+8 150
100
increases std to 5 and makes the mean 8 50
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
(1) Probability and Statistics
(2) Data Structures
(3) Images and Animation
(4) Debugging
(5) Online Resources
Advanced Data Structures
We have used 2D matrices
Can have n-dimensions
Every element must be the same type (ex. integers,
doubles, characters)
Matrices are space-efficient and convenient for calculation
Large matrices with many zeros can be made sparse:
a=zeros(100); a(1,3)=10;a(21,5)=pi; b=sparse(a);
Sometimes, more complex data structures are more
appropriate
Cell array: it's like an array, but elements don't have to
be the same type
Structs: can bundle variable names and values into one
structure
Like object oriented programming in MATLAB
Cells: organization
A cell is just like a matrix, but each field can contain
anything (even other matrices):
3x3 Matrix 3x3 Cell Array
2
J o h n
1.2 -3 5.5 4
32
-2.4 15 -10
M a r y 27 1
7.8 -1.1 4 18
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 initialize a cell, specify the size
a=cell(3,10);
a will be a cell with 3 rows and 10 columns
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:
s=struct([]);
size(s) will be 1x1
initialization is optional but is recommended when using large
structs
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
For more information, see doc struct
Struct Arrays
To initialize a struct array, give field, values pairs
ppl=struct('name',{'John','Mary','Leo'},...
'age',{32,27,18},'childAge',{[2;4],1,[]});
size(s2)=1x3
every cell must have the same size
person=ppl(2);
person is now a struct with fields name, age, children
the values of the fields are the second index into each cell
person.name
returns 'Mary' ppl ppl(1) ppl(2) ppl(3)
ppl(1).age
returns 32 name: 'John' 'Mary' 'Leo'
age: 32 27 18
childAge: [2;4] 1 []
Structs: access
To access 1x1 struct fields, give name of the field
stu=s.name;
scor=s.scores;
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; this may not always work,
the vectors must be able to be concatenated.
Exercise: Cells
Write a script called sentGen
Make a 3x2 cell, and put three names into the first column,
and adjectives into the second column
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 three names into the first column,
and adjectives into the second column
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
(4) Debugging
(5) Online Resources
Figure Handles
Every graphics object has a handle
L=plot(1:10,rand(1,10));
gets the handle for the plotted line
A=gca;
gets the handle for the current axis
F=gcf;
gets the handle for the current figure
To see the current property values, use get
get(L);
yVals=get(L,'YData');
To change the properties, use set
set(A,'FontName','Arial','XScale','log');
set(L,'LineWidth',1.5,'Marker','*');
Everything you see in a figure is completely customizable
through handles
Reading/Writing Images
Images can be imported into matlab
im=imread('myPic.jpg');
MATLAB supports almost all image formats
jpeg, 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 and
colormap
imwrite(rand(300,300,3),'test1.jpg');
imwrite(ceil(rand(200)*256),jet(256),...
'test2.jpg');
see help imwrite for more options
Animations
MATLAB makes it easy to capture movie frames and play
them back automatically
The most common movie formats are:
avi
animated gif
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
Plot frame by frame, and pause in between
close all
for t=1:30
imagesc(rand(200));
colormap(gray);
pause(.5);
end
Can also use drawnow instead of pause
When plotting lines or points, it's faster to change the
xdata and ydata properties rather than plotting each time
h=plot(1:10,1:10);
set(h,'ydata',10:1);
Saving Animations as Movies
A movie is a series of captured frames
close all
for n=1:30
imagesc(rand(200));
colormap(gray);
M(n)=getframe;
end
To play a movie in a figure window
movie(M,2,30);
Loops the movie 2 times at 30 frames per second
To save as an .avi file on your hard drive
movie2avi(M,'testMovie.avi','FPS',30, ...
'compression', 'cinepak');
See doc movie2avi for more information
Making Animated GIFs
You can use imwrite to save an animated GIF. Below is a
trivial example
temp=ceil(rand(300,300,1,10)*256);
imwrite(temp,jet(256),'testGif.gif',...
'delaytime',0.1,'loopcount',100);
Alternatively, you can use getframe, frame2im, and
rgb2ind to convert any plotted figure to an indexed image
and then stack these indexed images into a 4-D matrix and
pass them to imwrite. Read the doc on imwrite and these
other functions to figure out how to do this.
Outline
(1) Probability and Statistics
(2) Data Structures
(3) Images and Animation
(4) Debugging
(5) Online Resources
display
When debugging functions, use disp to print messages
disp('starting loop')
disp('loop is over')
disp prints the given string to the command window
It's also helpful to show variable values
disp(strcat(['loop iteration ',num2str(n)]));
strcat concatenates the given strings
Sometimes it's easier to just remove some semicolons
Debugging
To use the debugger, set breakpoints
Click on next to line numbers in MATLAB files
Each red dot that appears is a breakpoint
Run the program
The program pauses when it reaches a breakpoint
Use the command window to probe variables
Use the debugging buttons to control debugger
Clear breakpoint Stop execution; exit
Step to next
Two breakpoints
Where the program is now
Courtesy of The MathWorks, Inc. Used with permission.
Exercise: Debugging
Use the debugger to fix the errors in the following code:
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
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 seconds
Can have multiple tocs per tic
Performance Measures
For more complicated programs, use the profiler
profile on
Turns on the profiler. Follow this with function calls
profile viewer
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
(4) Debugging
(5) Online Resources
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/
End of Lecture 4
(1) Probability and Statistics
(2) Data Structures
(3) Images and Animation
(4) Debugging
(5) Online Resources
THE END
MIT OpenCourseWare
http://ocw.mit.edu
6.094 Introduction to MATLAB
January (IAP) 2010
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
6.094
Introduction to Programming in MATLAB
Lecture 5: Symbolics, Simulink,
File I/O, Building GUIs
Instructor:
Danilo epanovi
IAP 2010
Outline
(1) Symbolic Math
(2) Simulink
(3) File I/O
(4) Graphical User Interfaces
Symbolic Math Toolbox
Dont do nasty calculations by hand!
Symbolics vs. Numerics
Advantages Disadvantages
Symbolic Analytical solutions Sometimes can't be
Lets you intuit solved
things about Can be overly
solution form complicated
Numeric Always get a Hard to extract a
solution deeper understanding
Can make solutions Num. methods
accurate sometimes fail
Easy to code Can take a while to
compute
Symbolic Variables
Symbolic variables are a type, like double or char
To make symbolic variables, use sym
a=sym('1/3');
b=sym('4/5');
mat=sym([1 2;3 4]);
fractions remain as fractions
c=sym('c','positive');
can add tags to narrow down scope
see help sym for a list of tags
Or use syms
syms x y real
shorthand for x=sym('x','real'); y=sym('y','real');
Symbolic Expressions
Multiply, add, divide expressions
d=a*b
does 1/3*4/5=4/15;
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
We can do symbolics with matrices too
mat=sym('[a b;c d]');
mat2=mat*[1 3;4 -2];
compute the product
d=det(mat)
compute the determinant
i=inv(mat)
find the inverse
You can access symbolic matrix elements as before
i(1,2)
Exercise: Symbolics
The equation of a circle of radius r centered at (a,b) is
given by: ( x a ) + ( y b ) = r
2 2 2
Use solve to solve this equation for x and then for y
Its always annoying to integrate by parts. Use int to do
the following integral symbolically and then compute the
value by substituting 0 for a and 2 for b: b
dx
x
xe
a
Exercise: Symbolics
The equation of a circle of radius r centered at (a,b) is
given by: ( x a ) + ( y b ) = r
2 2 2
Use solve to solve this equation for x and then for y
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')
Its always annoying to integrate by parts. Use int to do
the following integral symbolically and then compute the
value by substituting 0 for a and 2 for b: b
dx
x
xe
a
Q=int(x*exp(x),a,b)
subs(Q,{a,b},{0,2})
Outline
(1) Symbolic Math
(2) Simulink
(3) File I/O
(4) Graphical User Interfaces
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
Courtesy of The MathWorks, Inc. Used with permission.
Getting Started
In MATLAB,
Start Simulink
Courtesy of The MathWorks, Inc. Used with permission.
Create a new
Simulink file,
similar to how
you make a new
script
Courtesy of The MathWorks, Inc. Used with permission.
Simulink Library Browser
The Library Browser contains various blocks that you can
put into your model
Examine some blocks:
Click on a library: Sources
Drag a block into Simulink: Band limited white noise
Visualize the block by going into Sinks
Drag a Scope into Simulink
Courtesy of The MathWorks, Inc. Used with permission.
Connections
Click on the carat/arrow on the right of the band
limited white noise box
Drag the line to the scope
Youll get a hint saying you can quickly connect
blocks by hitting Ctrl
Connections between lines represent signals
Click the play button
Courtesy of The MathWorks, Inc. Used with permission.
Double click on the scope.
This will open up a chart of the variable over the
simulation time
Connections, Block Specification
To split connections, hold down Ctrl when clicking on a
connection, and drag it to the target block; or drag
backwards from the target block
To modify properties of a block, double-click it and fill in
the property values.
Courtesy of The MathWorks, Inc. Used with permission.
Behind the curtain
Go to Simulation->Configuration Parameters
at the top menu
See ode45? Change the solver type here
Courtesy of The MathWorks, Inc. Used with permission.
Exercise: Simulink
Take your white noise signal, and split it into high
frequency and low frequency components. Use the
Transfer Function block from Continuous and use these
transfer functions:
1 0.1s
LP = HP =
0.1s + 1 0.1s + 1
Hook up scopes to the input and the two outputs
Send the two outputs to the workspace by using the to
Workspace block from Sink
Exercise: Simulink
The diagram should look like this. To change the transfer
function parameters, double click the blocks and specify
the numerator and denominator as polynomials in s
(remember how we defined polynomial vectors before)
Courtesy of The MathWorks, Inc. Used with permission.
Exercise: Simulink
After running the simulation, double-clicking the scopes will
show:
Input
Low pass
High Pass
Courtesy of The MathWorks, Inc. Used with permission.
Toolboxes
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
(1) Symbolic Math
(2) Simulink
(3) File I/O
(4) Graphical User Interfaces
Importing Data
MATLAB is a great environment for processing data. If you
have a text file with some data:
To import data from files on your hard drive, use
importdata
a=importdata('textFile.txt');
a is a struct with data, textdata, and colheaders fields
x=a.data;
names=a.colheaders;
Importing Data
With importdata, you can also specify delimiters. For
example, for comma separated values, use:
a=importdata('filename', ', ');
The second argument tells matlab that the tokens of
interest are separated by commas or spaces
importdata is very robust, but sometimes it can have
trouble. To read files with more control, use fscanf (similar
to C/Java), textread, textscan. See help or doc for
information on how to use these functions
Writing Excel Files
MATLAB contains specific functions for reading and writing
Microsoft Excel files
To write a matrix to an Excel file, use xlswrite
[s,m]=xlswrite('randomNumbers',rand(10,4),...
'Sheet1'); % we specify the sheet name
You can also write a cell array if you have mixed data:
C={'hello','goodbye';10,-2;-3,4};
[s,m]=xlswrite('randomNumbers',C,'mixedData');
s and m contain the 'success' and 'message' output of the
write command
See doc xlswrite for more usage options
Reading Excel Files
Reading excel files is equally easy
To read from an Excel file, use xlsread
[num,txt,raw]=xlsread('randomNumbers.xls');
Reads the first sheet
num contains numbers, txt contains strings, raw is the
entire cell array containing everything
[num,txt,raw]=xlsread('randomNumbers.xls',...
'mixedData');
Reads the mixedData sheet
[num,txt,raw]=xlsread('randomNumbers.xls',-1);
Opens the file in an Excel window and lets you click on the
data you want!
See doc xlsread for even more fancy options
Outline
(1) Symbolic Math
(2) Simulink
(3) File I/O
(4) Graphical User Interfaces
Making GUIs
It's really easy to make a graphical user interface in
MATLAB
To open the graphical user interface development
environment, type guide
guide
Select Blank GUI
Courtesy of The MathWorks, Inc. Used with permission.
Draw the GUI
Select objects from the left, and draw them where you
want them
Courtesy of The MathWorks, Inc. Used with permission.
Change Object Settings
Double-click on objects to open the Inspector. Here you can
change all the object's properties.
Courtesy of The MathWorks, Inc. Used with permission.
Save the GUI
When you have modified all the properties, you can save
the GUI
MATLAB saves the GUI as a .fig file, and generates an
MATLAB file!
Courtesy of The MathWorks, Inc. Used with permission.
Add Functionality to MATLAB file
To add functionality to your buttons, add commands to the
'Callback' functions in the MATLAB file. For example, when
the user clicks the Draw Image button, the
drawimage_Callback function will be called and executed
All the data for the GUI is stored in the handles, so use set
and get to get data and change it if necessary
Any time you change the handles, save it using guidata
guidata(handles.Figure1,handles);
Courtesy of The MathWorks, Inc. Used with permission.
Running the GUI
To run the GUI, just type its name in the command window
and the GUI will pop up. The debugger is really helpful for
writing GUIs because it lets you see inside the GUI
Courtesy of The MathWorks, Inc. Used with permission.
Outline
(1) Symbolic Math
(2) Simulink
(3) File I/O
(4) Graphical User Interfaces
Now you know EVERYTHING!
MIT OpenCourseWare
http://ocw.mit.edu
6.094 Introduction to MATLAB
January (IAP) 2010
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.