© All Rights Reserved

67 views

© All Rights Reserved

- Elementary Mathematics for Economics
- Linear Algebra & Matrices.ppt
- MATLAB Applications in Chemical Engineering
- Numerical Analysis Complex Matrix
- MAT1503 Exam Solutions
- MATLAB Course - Part 1
- Hi Guidelines
- Matrix Algebra
- Matlab Basics
- Chong
- Group Theory - Lecture Notes
- Guia Matrix Fitting MATLAB
- Quadratic inequalities.docx
- Introduction to Matrices
- 3 Matrices
- com Selangor STPM Trial 20111 Maths T
- MATLAB-1
- pnas.201019712SI
- Chapter 1
- HW5

You are on page 1of 205

Mousavinezhad)

These MATLAB tutorials are from MITs Open Courseware Site:

http://ocw.mit.edu

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.

6.094

Introduction to Programming in MATLAB

Sourav Dey

Danilo epanovi

Ankit Patel

Patrick Ho

IAP 2009

Lecture 1: Variables, Operations, and

Plotting

Course Layout

Lectures (7pm-9pm)

1: Variables, Operations and Plotting

2: Visualization & Programming

3: Solving Equations, Fitting

4: Advanced Methods

Course Layout

Problem Sets / Office Hours

One per day, should take about 3 hours to do

Submit doc or pdf (include pertinent code)

Requirements for passing

Attend all lectures

Complete all problem sets (FAIL, Check or +)

Prerequisites

Basic familiarity with programming

Basic linear algebra, differential equations, and

probability

Outline

(1) Getting Started

(2) Making Variables

(3) Manipulating Variables

(4) 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 &

Command Window

Current directory

Workspace

Command History

Courtesy of The MathWorks, Inc. Used with permission.

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

Scheme

Commands executed line by line

Conversing with MATLAB

who

MATLAB replies with the variables in your workspace

what

MATLAB replies with the current directory and

MATLAB files in the directory

why

help

The most important function for learning MATLAB on

your own

More on help later

Outline

(1) Getting Started

(2) Making Variables

(3) Manipulating Variables

(4) 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 arrays or matrices of

doubles or chars

Other types are also supported: complex, symbolic, 16-bit

and 8 bit integers, etc.

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

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

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

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.

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 4

a

=

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;

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 values

13 10 7 4 1

Save these two variables to file varEx

clear 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

Outline

(1) Getting Started

(2) Making Variables

(3) Manipulating Variables

(4) 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 cluttered 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);

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

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

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

transpose

The transpose operators turns a column vector into a row

vector 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

Addition and Subtraction

Addition and subtraction are element-wise; sizes must

match (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

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 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 2

2

3 4

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 (^) 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 this

later)

[ ]

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 2

2

3 4 3 4 3 4

^ *

Must be square to do powers

=

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-wise

b=[1 2 3].*[3 5 4]

Calculate the natural log of each element of the resulting

vector

c=log(b)

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 =zer os( 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

Exercise: Vector Functions

Make a vector that has 10,000 samples of

f(x) = e^{-x}*cos(x), for x between 0 and 10.

x = linspace(0,10,10000);

f = exp(-x).*cos(x);

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 n

th

element

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];

[ ]

13 5 9 10

a(1) a(2) a(3) a(4)

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 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

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

The index argument can be a matrix. In this case, each

element is looked up individually, and returned as a matrix

of 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 10

b

=

12 5

2 13

c

=

Advanced Indexing 2

MATLAB contains functions to help you find desired values

within 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

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<0.001)

BONUS Exercise: Matrices

Make a 3x100 matrix of zeros, and a vector x that has 100 values

between 0 and 10

mat=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 the

correct size

mat(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

(1) Getting Started

(2) Making Variables

(3) Manipulating Variables

(4) Basic Plotting

Plotting Vectors

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!!

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

Can change the line color, marker style, and line style by

adding a string argument

plot(x,y,k.-);

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

color

marker line-style

Other Useful plot Commands

Much more on this in Lecture 2, for now some simple

commands

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

Plot f(x) = e^x*cos(x) on the interval x = [0 10]. Use a red

solid line with a suitable number of points to get a good

resolution.

x=0:.01:10;

plot(x,exp(x).*cos(x),r);

End of Lecture 1

(1) Getting Started

(2) Making Variables

(3) Manipulating Variables

(4) Basic Plotting

Hope that wasnt too much!!

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.

6.094

Introduction to Programming in MATLAB

Lecture 2: Visualization and Programming

Sourav Dey

Danilo epanovi

Ankit Patel

Patrick Ho

IAP 2009

Outline

(1) Plotting Continued

(2) Scripts

(3) Functions

(4) Flow Control

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');

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

10

0

10

10

10

20

10

30

10

40

10

50

Playing with the Plot

to select lines

and delete or

change

properties

to zoom in/out

to slide the plot

around

to see all plot

tools at once

Courtesy of The MathWorks, Inc. Used with permission.

Line and Marker Options

Everything on a line can be customized

plot(x,y,'--rs','LineWidth',2,...

'MarkerEdgeColor','k',...

'MarkerFaceColor','g',...

'MarkerSize',10)

See doc line for a full list of

properties 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

Last time we saw how to add titles and labels using the GUI. Can

also do it command-line:

title('Stress-Strain');

xlabel('Force (N)');

For multiple lines, add a legend entry for each line

legend('Steel','Aluminum','Tungsten');

Can specify font and size for the text

ylabel('Distance (m)','FontSize',14,...

'FontName','Helvetica');

use ... to break long commands across multiple lines

To put parameter values into labels, need to use num2str and

concatenate:

str = [Strength of ' num2str(d) 'cm diameter rod'];

title(str)

Axis

A grid makes it easier to read values

grid on

xlim sets only the x axis limits

xlim([-pi pi]);

ylim sets only the y axis limits

ylim([-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 limits

between -1 and 1

Can specify tickmarks

set(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

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)

axis ij

puts the origin in the top left corner (for viewing matrices)

Multiple Plots in one Figure

Use the figure command to open a new figure

figure

or activate an open figure

figure(1)

To have multiple axes in one figure

subplot(2,3,1) or subplot(231)

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.

Figures: Exercise

Open a figure and plot a sine wave over two periods with

data points at 0, pi/8, 2pi/8 . Use black squares as

markers and a dashed red line of thickness 2 as the line

figure

plot(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

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);

Images: Exercise

Construct a Discrete Fourier Transform Matrix of size 128

using 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));

-1

-0.5

0

0.5

1

-1

-0.5

0

0.5

1

-10

-5

0

5

10

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');

Use tools on figure to rotate it

Can set limits on all 3 axes

xlim, ylim, zlim

Surface Plots

It is more common to visualize surfaces in 3D

Example:

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

How can we make these matrices

loop (DUMB)

built-in function: meshgrid

( ) ( ) ( )

[ ] [ ]

f x, y sin x cos y

x , ; y ,

=

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

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

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) Plotting Continued

(2) Scripts

(3) Functions

(4) Flow Control

Scripts: Overview

Scripts are

written in the MATLAB editor

saved as MATLAB files (.m extension)

evaluated line by line

To create an MATLAB file from command-line

edit myScript.m

or click

Courtesy of The MathWorks, Inc. Used with permission.

Scripts: the Editor

* Means that it's not saved

Line numbers

Debugging tools

Comments

MATLAB

file path

Help file

Possible breakpoints

Courtesy of The MathWorks, Inc. Used with permission.

Scripts: Good Practice

Take advantage of "smart indent" option

Keep code clean

Use built-in functions

Vectorize, vectorize, vectorize

When 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 file

Comment thoroughly to avoid wasting time later

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

Exercise: Scripts

A student has taken three exams. The performance on the

exams 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

(1) Plotting Continued

(2) Scripts

(3) Functions

(4) Flow Control

User-defined Functions

Functions look exactly like scripts, but for ONE difference

Functions must have a function declaration

Help file

Function declaration

Inputs Outputs

Courtesy of The MathWorks, Inc. Used with permission.

User-defined Functions

Some comments about the function declaration

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

Can have variable input arguments (see help varargin)

function [x, y, z] = funName(in1, in2)

Must have the reserved

word: function

Function name should

match MATLAB file

name

If more than one output,

must be in brackets

Inputs must be specified

Functions: Exercise

Take the script we wrote to calculate the student's overall

score 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 be

A 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

Courtesy of The MathWorks, Inc. Used with permission.

Functions

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

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);

D=size(a)

[m,n]=size(a)

[x,y,z]=size(a)

m2=size(a,2)

Take advantage of overloaded methods to make your code

cleaner!

Outline

(1) Plotting Continued

(2) Scripts

(3) Functions

(4) Flow Control

Relational Operators

MATLAB uses mostly standard relational operators

equal ==

not equal ~=

greater than >

less than <

greater or equal >=

less or equal <=

Logical operators normal bitwise

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

if cond

commands

end

ELSE

if cond

commands1

else

commands2

end

ELSEIF

if cond1

commands1

elseif cond2

commands2

else

commands3

end

No need for parentheses: command blocks are between

reserved words

Conditional statement:

evaluates to true or false

for

for loops: use for a definite number of iterations

MATLAB syntax:

for n=1:100

commands

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

The while is like a more general for loop:

Don't need to know number of iterations

The command block will execute while the conditional

expression is true

Beware of infinite loops!

WHILE

while cond

commands

end

Exercise: Control-Flow

Write a function to calculate the factorial of an integer N using a

loop (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<0,

a=nan,

else

a = 1;

for k=1:N

a = a*k;

end

end

But note that factorial() is already implemented! You should see if

there are built-in functions before implementing something

yourself.

which factorial

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

Exercise: Flow Control

Given x= sin(linspace(0,10*pi,100)), how many of the

entries are positive?

Using a loop and if/else

count=0;

for n=1:length(x)

if x(n)>0

count=count+1;

end

end

Being more clever

count=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

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

end

Slow 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

prod

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 loops

Over-vectorizing code can obfuscate it, i.e. you wont be

able to understand or debug it later

Sometime a loop is the right thing to do, it is clearer and

simple

End of Lecture 2

(1) Plotting Continued

(2) Scripts

(3) Functions

(4) Flow Control

Vectorization makes

coding fun!

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.

6.094

Introduction to Programming in MATLAB

Lecture 3 : Solving Equations and Curve Fitting

Sourav Dey

Danilo epanovi

Ankit Patel

Patrick Ho

IAP 2009

Outline

(1) Linear Algebra

(2) Polynomials

(3) Optimization

(4) Differentiation/Integration

(5) Differential Equations

Systems of Linear Equations

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=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.

MATLAB makes linear

algebra fun!

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+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:

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 matrix

x1=A\b;

gives least squares solution

A*x1

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

ax

3

+bx

2

+cx+d

P=[1 0 -2] represents the polynomial x

2

-2

P=[2 0 0 0] represents the polynomial 2x

3

P(1) P(2) P(3) P(4)

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 = 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.

Add random noise to these samples. Use randn. Plot the

noisy signal with . markers

fit a 2

nd

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

Evaluate x^2 over x=-4:0.1:4 and save it as y.

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 2

nd

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

the 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);

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

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 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).*exp(-abs(x)) over the range pi to

pi. Use fminbnd. Is your answer really the minimum

over 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

pi. Use fminbnd. Is your answer really the minimum

over 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) Polynomials

(3) Optimization

(4) Differentiation/Integration

(5) Differential Equations

Numerical Differentiation

MATLAB can 'differentiate' numerically

x=0:0.01:2*pi;

y=sin(x);

dydx=diff(y)./diff(x);

diff computes the first difference

Can also operate on matrices

mat=[1 3 5;4 8 6];

dm=diff(mat,1,2)

first difference of mat along the 2

nd

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

0.6

0.8

1

Numerical Integration

MATLAB contains common integration methods

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 pi

z2=trapz(x,sqrt(exp(x))./x)

z2 is the integral of from 0 to pi

x

e x

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])

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 fcn.

ODE integrator:

23, 45, 15s

ODE function

Time range

Initial conditions

ODE Function

The ODE function must return the value of the derivative at

a given time and function value

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

dA

A B

dt

dB

A B

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

0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5

0

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

Time (s)

A

m

o

u

n

t

o

f

c

h

e

m

i

c

a

l

(

g

)

Chem reaction

A

B

Higher Order Equations

Must make into a system of first-order equations to use

ODE solvers

Nonlinear is OK!

Pendulum example:

( )

( )

( )

0

g

sin

L

g

sin

L

let

g

sin

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]);

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 of

angle (rad)

Velocity (m/s)

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:

-3 -2 -1 0 1 2 3

-8

-6

-4

-2

0

2

4

6

8

Position

V

e

l

o

c

i

t

y

Velocity is greatest

when theta=0

Velocity=0 when

theta is the greatest

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 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 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 this differential equation on the range

t=[0 10], with initial condition y(0) = 10: dy/dt=-t*y/10.

Plot the result.

Exercise: ODE

Use ODE45 to solve this differential equation on the range

t=[0 10], with initial condition y(0) = 10: dy/dt=-t*y/10.

Plot the result.

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

(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

use odeset to control errors

decrease error tolerances to get more accurate

results

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.

6.094

Introduction to Programming in MATLAB

Lecture 4: Advanced Methods

Sourav Dey

Danilo epanovi

Ankit Patel

Patrick Ho

IAP 2009

Outline

(1) Probability and Statistics

(2) Data Structures

(3) Images and Animation

(4) Debugging

(5) Symbolic Math

(6) Other Toolboxes

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.

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)

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

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 25

0

50

100

150

200

250

300

350

400

-25 -20 -15 -10 -5 0 5 10 15 20 25

0

10

20

30

40

50

60

70

80

90

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 k

th

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 k

th

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) Symbolic Math

(6) Other Toolboxes

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

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):

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

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 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)

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

Exercise: Cells

Write a script called sentGen

Make a 3x2 cell, and put peoples 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 peoples 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) Symbolic Math

(6) Other Toolboxes

Importing/Exporting 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(mat,jet(256),'test.jpg','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

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);

See book appendix or docs for more information

Handles

Every graphics object has a handle

h=plot(1:10,rand(1,10));

gets the handle for the plotted line

h2=gca;

gets the handle for the current axis

h3=gcf;

gets the handle for the current figure

To see the current property values, use get

get(h);

yVals=get(h,'YData');

To change the properties, use set

set(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

(4) Debugging

(5) Symbolic Math

(6) Other Toolboxes

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

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:

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) 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

rather than redefining the functions yourself

saves coding/debugging time

some functions are compiled, so they run faster

HOWEVER 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

Symbolic Analytical solutions

Lets you intuit

things about

solution form

Sometimes can't be

solved

Can be overly

complicated

Numeric Always get a

solution

Can make solutions

accurate

Easy to code

Hard to extract a

deeper understanding

Num. methods

sometimes fail

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');

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

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)

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 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)^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

terms of a,b, and r.

Exercise: Symbolics

The equation of a circle of radius r centered at (a,b) is

given 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

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

(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

Laplace transforms

Related Toolboxes

Communications

Wavelets

RF

Image Processing

Control System Toolbox

The control systems toolbox contains functions helpful for

analyzing systems with feedback

Simulation of LTI system function

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 Identification

Robust Control modern control theory

Model Predictive Control

Statistics Toolbox

For hardcore statistics and data-analysis

Principal component analysis

Independent component analysis

Tests of significance (chi squared, t-tests)

Related Toolboxes

Spline for fitting

Bioinformatics

Neural Networks

Optimization Toolbox

For more hardcore optimization problems that occur in

OR, business, engineering

linear programming

interior point methods

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

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/

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

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

THE END

Monte-Carlo Simulation

A simple way to model complex stochastic systems

Use random numbers to control state changes

This system represents a complex reaction

The numbers by the arrows show the propensity of the

system 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

B A

60

60

60

60

47

47

47

47

2

2

2

2

20 20

20

20

Example: Monte-Carlo

This MATLAB file will track the behavior of the molecule

Courtesy of The MathWorks, Inc. Used with permission.

Example: Monte-Carlo

We can run the code 1000 times to simulate 1000 molecules

s=zeros(200,5);

for n=1:1000

st=MC(200);

for state=0:4

s(:,state+1)= s(:,state+1)+(st==state);

end

end

0 20 40 60 80 100 120 140 160 180 200

0

100

200

300

400

500

600

700

800

900

1000

A

0 20 40 60 80 100 120 140 160 180 200

0

50

100

150

200

250

300

350

400

450

B

0 20 40 60 80 100 120 140 160 180 200

0

50

100

150

200

250

300

350

C

0 20 40 60 80 100 120 140 160 180 200

0

50

100

150

200

250

300

350

400

D

0 20 40 60 80 100 120 140 160 180 200

0

100

200

300

400

500

600

700

800

900

1000

E

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.

6.094

Introduction to Programming in MATLAB

Lecture 5: Simulink

Sourav Dey

Danilo epanovi

Ankit Patel

Patrick Ho

IAP 2009

What is Simulink?

A model-based equation solver

Some analysis packages (ANSYS, Multisim) have

built in equations modeling complex engineering

problems.

Save lots of time

Can only be used for tackling specific problems

Simulink lets you build a GUI-based model and

simulates the result.

Unlimited complexity (constrained by runtime and

memory)

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

Drag a block into Simulink: Constant

Visualize the block by going into Sinks

Drag a Scope into Simulink

Connections

Click on the carat/arrow on the right of the

constant 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

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 and

the scope

Play and click on scope.

What happens?

Simulink has a built in ODE solver

The equation that represents your model is solved by

Simulink

Weve represented

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.

So whats going on?

The toolboxes Simulink provides you are full of

modeling tools

By selecting components that correspond to your

model, you can design a simulation

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

Modifying Blocks

Right click on the block, select the Parameters item

corresponding to the item type

Transfer Function:

Numerator on

first row

Denominator on

second row

Summing Junction:

List of signs

determines

inputs to

junction

Not shown:

Sampling time row

Courtesy 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

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 summing

junction between the

constant and

integrator

Change the signs to

|+-

Click on the open

carat under the minus

sign and connect it to

the integrator output

Creating Subsystems

Drag a box around the

parts of the subsystem

Summing Junction

Integrator

Right click and select

create subsystem

Double click the

subsystem:

The parts are now

inside

Whats the system do

when you run it?

Example Systems

ODE

d

3

y/dt

3

+ a*d

2

y/dt

2

+

b* dy/dt + c*y = F

Classical Control System

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

Locomotive behaviors are generated by central pattern

generators, which oscillate on their own naturally

When connected to an appendage, the central pattern

generator will adapt its frequency and move the

appendage. Open RIOCPGDemo.mdl

Model based on Iwasaki, T., Zheng, M. (2006a). Sensory feedback

mechanism underlying entrainment of central pattern generator to

mechanical resonance. Biological Cybernetics, 94(4), 245-261

Central Pattern Generator Model

Limb

Scope for

Output

Playing with the model

Look at scopes

What are the output signals?

Delete signals

Especially the signal after the feedback gain

Change gains

Muscular actuator gains

Switch feedback gain from negative to positive

Look inside subsystems

Whats inside the CPG?

Whats inside the neuron firing dynamics?

Toolboxes

Simulink has many advanced toolboxes

Control Systems

Neural Networks

Signal Processing

SimMechanics

Virtual Reality

Real Time

Hopefully youll get to use some of these powerful tools!

- Elementary Mathematics for EconomicsUploaded byDavid Jack
- Linear Algebra & Matrices.pptUploaded bykamayani_pr
- MATLAB Applications in Chemical EngineeringUploaded byJuanMuñoz
- Numerical Analysis Complex MatrixUploaded bybitconcepts9781
- MAT1503 Exam SolutionsUploaded byd_systemsuganda
- MATLAB Course - Part 1Uploaded byramorado
- Hi GuidelinesUploaded byVikas Patel
- Matrix AlgebraUploaded byGaurav Shrivastava
- Matlab BasicsUploaded bySandeep Kumar
- ChongUploaded byEpic Win
- Group Theory - Lecture NotesUploaded byEmily Huang
- Guia Matrix Fitting MATLABUploaded byThomaz Pithon
- Quadratic inequalities.docxUploaded byAngel Comia
- Introduction to MatricesUploaded byMohammed Gamal
- 3 MatricesUploaded byHarsh Ravi
- com Selangor STPM Trial 20111 Maths TUploaded byTan Khuai
- MATLAB-1Uploaded byjohnanother
- pnas.201019712SIUploaded byTridip Sardar
- Chapter 1Uploaded byMaloem Sinaga
- HW5Uploaded by123chess
- 3 13h - all systems goUploaded byapi-272842326
- IIpuc Modelqp MathUploaded byRanjan Prasad
- Symoro_RoboticaUploaded byJasón De Elea
- alg-combUploaded byPurbayan Chakraborty
- 2015 Unit 1 Exam RevisionUploaded bypoonam_goyal26
- spring16.pdfUploaded byالعلم نور
- Mat188 Tut7 AnsUploaded byCarlos Buitrago
- Pid BackUploaded byPauline Luna
- nica_precupUploaded byoctavia_octavia
- HW 05.pdfUploaded byQFTW

- UXP100U_200.pdfUploaded byAndrea Griffin
- Capstone_ Kumar Saurav_1507 REUploaded bysauravsahai
- LINUX CMDUploaded byAga A
- AmazingEA ReadMe InstructionsUploaded byNicholson977
- ASCII control characters.pdfUploaded byȐÌzwâñ Såléèm
- 3 4 7 acutandfilloptional docUploaded byapi-299811796
- An Improved Numerical Model for Calculating Ship_hull Frame Transversal StructureUploaded byAdemar Cardoso
- Zdenek Dostál - Optimal Quadratic Programming Algorithms_ With Applications to Variational Inequalities (2009, Springer)Uploaded byJuan Carlos Colque
- Ooad With Uml Question BankUploaded byNeeraj Menon
- Lab 2 Level 1 Space Mean SpeedUploaded byMohd Syafiq Akmal
- Myphone q19i Duo (3)Uploaded byJohn Roque Aliazas
- admap 2015.pdfUploaded byAlmas Shafiq Ahmed
- #_an Efficient Server Floor Popup 1Uploaded bydocham
- Thevenins and NortonUploaded byJayson Bryan Mutuc
- Delta Web ServicesUploaded byRajShah
- LG DN192Uploaded bypinopn
- MIT6_088IAP10_lec02Uploaded byeviludion
- ETU02_muxUploaded byapi-3749499
- Sample Process Guide - Configuration ManagementUploaded byZunair Jawaid
- RoSy Design Product Sheet 2011Uploaded byMihai Popescu
- CCNA Cisco Routing Protocols and Concepts Assessment 1Uploaded bysabriel69
- 17 - Modern Envelope Analysis for Bearing DiagnosticsUploaded byDimas Benasulin
- Epson 24774 EuUploaded byEduardo Mendoza
- SIEMENS-TIA Portal First Steps (Turck)Uploaded byJorge Andril
- Broadcasting Digital Media Industry in India - Full Report.pdfUploaded bySiddhant Gupta
- Mega eBookUploaded byDany Cahyadi
- IPR2015-01962-NotInstitutedUploaded byTradeHawk
- IIT MMAE 501 Set 2 Solution(1)Uploaded byMatt Bishop
- Mechanical Engineering R16 SYLLABUSUploaded byRajesh Shah
- Bandpass Digital communication system solved problems Tutorial sheetUploaded byمهند عدنان الجعفري