introduction to matlab - university of new mexiconvladimi/math375/matlab.pdf · click on the...

40
Introduction to MATLAB Math 375 Getting started Arithmetics Matrices Plotting Functions Program Control Introduction to MATLAB Math 375 Natalia Vladimirova (many ideas, examples, and excersises are borrowed from Profs. Monika Nitsche, Richard Allen, and Stephen Lau) January 24, 2010

Upload: hatuong

Post on 07-Jun-2018

232 views

Category:

Documents


0 download

TRANSCRIPT

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Functions

Program Control

Introduction to MATLAB

Math 375Natalia Vladimirova

(many ideas, examples, and excersises are borrowed fromProfs. Monika Nitsche, Richard Allen, and Stephen Lau)

January 24, 2010

Introduction toMATLAB

Math 375

Getting started

Starting MATLAB

Desktop Tools

Getting Help

Saving your work

Arithmetics

Matrices

Plotting

Functions

Program Control

Starting MATLABI Under windows

Click on the ”Start” menu buttonClick on the ”MATLAB” menu entry

I Under LinuxUse SSH to log onto linux.unm.eduType matlab

Introduction toMATLAB

Math 375

Getting started

Starting MATLAB

Desktop Tools

Getting Help

Saving your work

Arithmetics

Matrices

Plotting

Functions

Program Control

Desktop ToolsI Command Window

type commands

I Workspaceview program variablesdouble click on a variable to see it in the Array Editor

I Command Historyview past commands

I Current Directoryview and select files in the current directorythe current directory can be changed in the toolbar

I To switch to the default windows arrangement, go to menuDesktop > Desktop Layout > Default

Introduction toMATLAB

Math 375

Getting started

Starting MATLAB

Desktop Tools

Getting Help

Saving your work

Arithmetics

Matrices

Plotting

Functions

Program Control

Getting HelpI Using the Help Browser

I From command window

>> help

>> help plot

I Running demos

>> demos

>> help demos

I On the webhttp://www.mathworks.com

Introduction toMATLAB

Math 375

Getting started

Starting MATLAB

Desktop Tools

Getting Help

Saving your work

Arithmetics

Matrices

Plotting

Functions

Program Control

Saving your workI in class, create your directory (folder) in T: drive

I MATLAB files reside on the current directory or the searchpath

>> addpath T:\myfolder

>> addpath ~/matlab

I you can save a whole session using

>> diary "diary_Jan23.txt"

>> diary off

>> diary on

I bring your flash card (floppy, CD-RW) to save class work

I or upload your files to your UNM storage (?)

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Variables

Build-in constants

Arithmetic operators

Logical operators

Math functions

Scripts

Matrices

Plotting

Functions

Program Control

VariablesI creating a variable (MATLAB is case sensitive);

semicolon suppresses output

>> x = 5;

>> x = 5

x =

5

I checking variables

>> whos

I deleting a variable

>> clear x

I deleting all variables

>> clear

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Variables

Build-in constants

Arithmetic operators

Logical operators

Math functions

Scripts

Matrices

Plotting

Functions

Program Control

Build-in constants

Imaginary unit i = j =√−1 and π

>> clear

>> pi

pi = 3.1416

>> i

i = 0 + 1i

>> j

j = 0 + 1i

Build-in constants can be overridden

>> i = 8

i = 8

>> clear

>> i

i = 0 + 1i

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Variables

Build-in constants

Arithmetic operators

Logical operators

Math functions

Scripts

Matrices

Plotting

Functions

Program Control

Arithmetic operators

+ addition

− subtraction

* multiplication

/ division

ˆ power

‘ complex conjugate and transpose

.* element-by-element mult

./ element-by-element div

.̂ element-by-element power

.‘ transpose

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Variables

Build-in constants

Arithmetic operators

Logical operators

Math functions

Scripts

Matrices

Plotting

Functions

Program Control

Relational and logical operators

== equal

∼= not equal

< less than

<= less than or equal

> greater than

>= greater than or equal

& AND

| OR

∼ NOT

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Variables

Build-in constants

Arithmetic operators

Logical operators

Math functions

Scripts

Matrices

Plotting

Functions

Program Control

Mathematical functionsI Elementary functions (sin, cos, sqrt, abs, exp, log10, round)

>> help elfun

I Advanced functions (bessel, beta, gamma, erf)

>> help specfun

>> help elmat

I Example

>> x=2.3; a=sin(x), b=cos(x)

a = 0.7457

b = -0.6663

>> c = ( sin(x) )^2 + ( cos(x) )^2

c = 1.0000

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Variables

Build-in constants

Arithmetic operators

Logical operators

Math functions

Scripts

Matrices

Plotting

Functions

Program Control

MATLAB scriptsI Example of MATLAB script file (myscript.m)

myscript.m

% This is a comment.

% convert cartesian coordinares (x,y)

% to polar coordinates (r,theta)

x = 4;

y = 3;

r = sqrt(x^2 + y^2)

theta = atan(y/x)

% continuation character is ‘‘...’’

I Save it in your working directoryI Call it from the command window

>> myscript

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Creating vectors

More ways...

Creating matrices

Addition

Multiplication

Accessing elements

... more

Matrix operations

Matrix size

Exercises

Plotting

Functions

Program Control

Creating vectors

>> x = [1 2 5 3] % separated by spaces

x =

1 2 5 1

>> x = [1, 2, 5, 3] % separated by commas

x =

1 2 5 3

>> y = [6; 7; 4; 8] >> y = x’

y = y =

6 1

7 2

4 5

8 3

Note: A’ = transpose ( A )

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Creating vectors

More ways...

Creating matrices

Addition

Multiplication

Accessing elements

... more

Matrix operations

Matrix size

Exercises

Plotting

Functions

Program Control

More ways of creating vectorsI Using increment x1 : ∆x : xn

>> x = 0:0.2:1

x =

0.0 0.2 0.4 0.6 0.8 1.0

I Using linspace (x1, xn, n)

>> x = linspace(0,1,6)

x =

0.0 0.2 0.4 0.6 0.8 1.0

I Note: both end points are included, ∆x = xn−x1

n−1

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Creating vectors

More ways...

Creating matrices

Addition

Multiplication

Accessing elements

... more

Matrix operations

Matrix size

Exercises

Plotting

Functions

Program Control

Creating matricesI Explicitly

>> A = [1 2 3; 4 5 6; 7 8 9]

A =

1 2 3

4 5 6

7 8 9

I Using MATLAB functions

>> M = 2; N = 3;

>> a = zeros(M, N)

>> b = ones(M, N)

>> c = rand(M, N)

>> I = eye(N)

I scalar is 1× 1 matrix

I vector is 1× N or N × 1 matrix

I you can create N1 × N2 × ...× Nn matrices

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Creating vectors

More ways...

Creating matrices

Addition

Multiplication

Accessing elements

... more

Matrix operations

Matrix size

Exercises

Plotting

Functions

Program Control

Matrix addition (or subtraction)

element by element C = A + B : Cij = Aij + Bij

(a11 a12

a21 a22

)+

(b11 b12

b21 b22

)=

(a11 + b11 a12 + b12

a21 + b21 a22 + b22

)

>> A = [1 2; 3 4] >> B = [5 6; 7 8]

A = B =

1 2 5 6

3 4 7 8

>> C = A + B

C =

6 8

10 12

Matrices being added must be the same size

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Creating vectors

More ways...

Creating matrices

Addition

Multiplication

Accessing elements

... more

Matrix operations

Matrix size

Exercises

Plotting

Functions

Program Control

Matrix multiplication

not element by element C = AB: Cij =∑n

k=1 AikBkj

(a11 a12

a21 a22

)(b11 b12

b21 b22

)=

(a11b11 + a12b21 a11b12 + a12b22

a21b11 + a22b21 a21b12 + a22b22

)

>> A = [1 2; 3 4] >> B = [4 3; 2 1]

A = B =

1 2 4 3

3 4 2 1

>> C = A * B >> C = A .* B

C = C =

8 5 4 6

20 13 6 4

For element by element multiplication use .*

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Creating vectors

More ways...

Creating matrices

Addition

Multiplication

Accessing elements

... more

Matrix operations

Matrix size

Exercises

Plotting

Functions

Program Control

Accessing elements of a matrix

>> A = [1 2 3; 4 5 6; 7 8 9]

A =

1 2 3

4 5 6

7 8 9

I A(i , j) subscription - numbering starts from 1 (Fortran style)

>> A(2,3)

ans = 6

I whole row

>> x = A(2,:)

x =

4 5 6

I whole column

>> y = A(:,3)

y =

3

6

9

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Creating vectors

More ways...

Creating matrices

Addition

Multiplication

Accessing elements

... more

Matrix operations

Matrix size

Exercises

Plotting

Functions

Program Control

Accessing elements of a matrix (cont.)

I Matrix elements can be accessed by index array.Try the following:

>> v = 10:10:80

>> ind = [3,4,7]

>> v(ind)

>> v(ind) = -1

I ... or by condition:

>> v = 10:10:80

>> v>30

>> v(v>30) = -1

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Creating vectors

More ways...

Creating matrices

Addition

Multiplication

Accessing elements

... more

Matrix operations

Matrix size

Exercises

Plotting

Functions

Program Control

Matrix operationsI [ ] concatenation

>> x = [ zeros(1,3) ones(1,2) ]

x =

0 0 0 1 1

I ( ) subscription

>> x = [ 1 3 5 7 9];

>> y = x(2)

y =

3

>> y = x(2:4)

y =

3 5 7

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Creating vectors

More ways...

Creating matrices

Addition

Multiplication

Accessing elements

... more

Matrix operations

Matrix size

Exercises

Plotting

Functions

Program Control

Finding matrix size

Explain the output of the following command

>> A = [1 2 3; 4 5 6]

>> ndims(A)

>> length(A)

>> size(A)

>> [n m] = size(A)

>> sum(A)

>> sum(A,1)

>> sum(A,2)

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Creating vectors

More ways...

Creating matrices

Addition

Multiplication

Accessing elements

... more

Matrix operations

Matrix size

Exercises

Plotting

Functions

Program Control

What happens when you run the followingcommands? Why?

>> x = 0:1:5

>> y = x*x

>> y = x.*x

>> y = x^2

>> y = x’*x

>> y = x*x’

>> y = 2*x

>> y = 1./x

>> x = 0:0.1:1

>> y = x(4:8)

>> y = x(5:end)

>> y = x([1,5,7,11])

>> A = [1 2 3; 4 5 6; 7 8 9]

>> B = A((2:3),(2:3))

>> C = sin([0, 0.5*pi, pi, 1.5*pi])

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Simple plot

Label you plots!

Saving plots

Markers

Multiple Plots

In class exercise

Functions

Program Control

Simple plotI MATLAB plots arrays. Arrays must be created first!

>> t = 1:1:7

>> plot(t, sin(t))

I More points - smoother line

>> x = 1:0.1:7;

>> y = sin(x);

>> plot(x, y)

I Note: y(x) is plotted, not x(t) and y(t).

I Vectors x and y must be the same length.

I To create a graph in logaritmic coordimatesuse loglog, semilogx, or semilogy instead of plot.

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Simple plot

Label you plots!

Saving plots

Markers

Multiple Plots

In class exercise

Functions

Program Control

Label you plots!I Once we created the plot...

>> x = linspace(0, 2*pi, 50);

>> y = sin(x);

>> plot(x, y, ’o-r’) % plot with red circles

I we can add features to it

>> axis([0, 2*pi, -1.1, 1.1])

>> xlabel(’x’); ylabel(’y’)

>> title(’Plot of the sine function’)

>> legend(’y(x) = sin(x)’, ’Location’, ’NorthEast’)

>> grid on

I You can edit figure using menu functions.

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Simple plot

Label you plots!

Saving plots

Markers

Multiple Plots

In class exercise

Functions

Program Control

Saving plots to files

I Save your figure as *.fig - this way you can modify it later.

I Save PDF on letter-size paper. Here “gcf” is the handle tocurrent figure (“get current figure”). The plot position on thepaper is given as the coordinates of upper-left and lower-rightcorners

>> set(gcf, ’papersize’, [8.5, 11], ...

’paperposition’, [1, 1, 6, 4])

>> saveas(gcf,’myplot.pdf’,’pdf’)

I If figure to be inserted into a document, use paper size sameas plot size

>> set(gcf, ’papersize’, [6, 4], ...

’paperposition’, [0, 0, 6, 4])

>> saveas(gcf,’myplot.pdf’,’pdf’)

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Simple plot

Label you plots!

Saving plots

Markers

Multiple Plots

In class exercise

Functions

Program Control

Marker options (type help plot to remind)

b blue . point - solid

g green o circle : dotted

r red x x-mark -. dashdot

c cyan + plus -- dashed

m magenta * star (none) no line

y yellow s square

k black d diamond

w white v triangle (down)

^ triangle (up)

< triangle (left)

> triangle (right)

p pentagram

h hexagram

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Simple plot

Label you plots!

Saving plots

Markers

Multiple Plots

In class exercise

Functions

Program Control

Multiple graphs, panels, and figuresI Multiple graphs on the same plot (also see help hold)

>> x = linspace(0, 2*pi, 100);

>> y1 = cos(3*t) .* exp(-0.5*t);

>> y2 = sin(3*t) .* exp(-0.5*t);

>> plot(t,y1,’x’, t,y2, ’*’)

I To open new figure (new window)

>> figure

>> figure(1) %make figure 1 current figure

I To divide figure to panels

>> subplot(2,2,1)

>> plot(t,y1)

>> subplot(2,2,2)

>> plot(t,y2)

>> subplot(2,2,3)

>> plot(y1,y2)

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Simple plot

Label you plots!

Saving plots

Markers

Multiple Plots

In class exercise

Functions

Program Control

In class exercise

By plotting y(t) below with different values of parameter a find aat which y(t) passes through given “experimental” points as closeas possible

y(t) = e−t2 sin(at)

t = 0.1 0.5 0.9 1.3 1.7 ...

2.1 2.5 2.9 3.3 3.7

y = 0.648 -0.445 0.287 -0.167 0.078 ...

-0.015 -0.028 0.056 -0.072 0.079

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Functions

User defined ...

... more

... more

Function handles

Program Control

User defined functionsI Unlike scripts, functions can take arguments and return values

I Like scripts, MATLAB functions reside in M-files (*.m)

I Name of the file = name of the function

I Example of function file mycomplex.m

mycomplex.m

function z = mycomplex(x,y)

z = x + i*y;

end

here x and y are arguments, z is returned value,and mycomplex is the name of the function

I Call it from command line or from another function

>> c = mycomplex(a,b)

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Functions

User defined ...

... more

... more

Function handles

Program Control

User defined functions (cont.)I Functions can take matrices as arguments

I Functions can return multiple values

I You can put several functions in a single M-file.

I Example: function file myplot.m

myplot.mfunction myplot

[x,y] = mydata(n);

plot(x,y);

end

function [x,y] = mydata(n)

x = linspace(0, 2*pi, n);

y = sin(x);

end

I Can we call mydata(n) from command line?

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Functions

User defined ...

... more

... more

Function handles

Program Control

User defined functions (cont.)I Example: function file mycart2pol.m

mycart2pol.m

function[ radius, theta ] = mycart2pol(x, y)

% convert cartesian coordinares (x, y)

% to polar coordinates (r, theta)

theta = atan2(y, x);

radius = sqrt(x.^2 + y.^2);

end

I What happens when you call mycart2pol as following?

>> mycart2pol(1,1)

>> r = mycart2pol(1,1)

>> [r th] = mycart2pol(1,1)

>> [r th] = mycart2pol([-1 -2 -3], [0 0 0])

>> help mycart2pol

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Functions

User defined ...

... more

... more

Function handles

Program Control

Function handlesI There are a number of useful MATLAB functions which take

function handle as an argumentI Example: to numerically evaluate integral∫ 2

1

x3dx =1

4

(24 − 14

)= 3.75

using MATLAB function quad we first create file cube.m

cube.mfunction y = cube(x)

y = x.^3;

end

I and then pass the function handle (@cube) and integrationlimits (1,2) to quad

>> quad(@cube, 1, 2)

I or create inline function, defined by the string

>> f = inline(’x.^3’);

>> quad(f, 1, 2)

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Functions

Program Control

For loop

For loop: examples

For loop: examples

While loop

If statement

If-else statement

If-else example

Other statements

Simple text I/O

For loopI The for loop executes a statement or group of statements a

predetermined number of times.

for x = x1 : ∆x : xnstatement

end

I The increment ∆x can be omitted; default ∆x = 1

for x = x1 : xnstatement

end

I The index of a for loop can be an array.

v=v1 : ∆v : vnfor x = v

statementend

I For loops can be nested

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Functions

Program Control

For loop

For loop: examples

For loop: examples

While loop

If statement

If-else statement

If-else example

Other statements

Simple text I/O

For loop: examples

>> format compact

>> for n = 1:5

disp(n)

end

>> for n = 0.5:0.1:0.8

disp(n)

end

>> v = [2, 4, 8, 16];

>> for n = v

disp(n)

end

>> for j = 1:3

for i = 1:3

A(i,j) = i+j;

end

end

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Functions

Program Control

For loop

For loop: examples

For loop: examples

While loop

If statement

If-else statement

If-else example

Other statements

Simple text I/O

For loop: examples

Create vector [1 2 3 4 5] in a “classical” way

>> v = zeros(1,5) % allocate space

>> for i=1:5 % cycle through the elements

v(i)=i % assign value to each element

end

Note: allocation is optional (but it makes the code run faster).Try the following:

>> clear v

>> for i=1:5

v(i)=i

end

>> v = zeros(1,5)

>> a = v(8)

>> v(8) = 8

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Functions

Program Control

For loop

For loop: examples

For loop: examples

While loop

If statement

If-else statement

If-else example

Other statements

Simple text I/O

While loop

The while loop executes a statement or group of statementsrepeatedly as long as the controlling expression is true

while conditionstatement

end

>> x=1;

>> while x > 0.01

x = x/2

end

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Functions

Program Control

For loop

For loop: examples

For loop: examples

While loop

If statement

If-else statement

If-else example

Other statements

Simple text I/O

If statement

If evaluates a logical expression and executes a group ofstatements based on the value of the expression.

if conditionstatement

end

Example: find the maximum element in an array:

>> v=rand(1,6)

>> vmax = -1;

>> for i=1:length(v)

if v(i) > vmax

vmax = v(i);

end

end

>> disp(vmax)

But, of coarse, it is easier just to do

>> vmax = max(max(v))

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Functions

Program Control

For loop

For loop: examples

For loop: examples

While loop

If statement

If-else statement

If-else example

Other statements

Simple text I/O

If-else statement

if-else can take care for both branches of the fork...

if condition1statement1

elsestatement2

end

... or multiple branches

if condition1statement1

elseif condition2statement2

elseif condition3statement3

elsestatement4

end

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Functions

Program Control

For loop

For loop: examples

For loop: examples

While loop

If statement

If-else statement

If-else example

Other statements

Simple text I/O

If-else example

Script rps.m simulates a rock-paper-scissors player

rpm.s

% simulate a rock-paper-scissors player

x = rand(1) % get random number between 0 to 1

x = x*3 % rescale x so that 0 < x < 3

if x<1

disp(’rock!’)

elseif x<2

disp(’paper!’)

else

disp(’scissors!’)

end

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Functions

Program Control

For loop

For loop: examples

For loop: examples

While loop

If statement

If-else statement

If-else example

Other statements

Simple text I/O

Other program control statements

continue passes control to the next iteration of the loop

break terminates the execution of a loop

return exits the currently running function

switch executes statements based on the value of a variable orexpression

try, catch error control statements

Note: there is no goto statement in MATLAB

Introduction toMATLAB

Math 375

Getting started

Arithmetics

Matrices

Plotting

Functions

Program Control

For loop

For loop: examples

For loop: examples

While loop

If statement

If-else statement

If-else example

Other statements

Simple text I/O

Simple text input and outputI C-style output to the screen

>> fprintf(’square root of %d is %6.3f\n’, 3, sqrt(3))

square root of 3 is 1.732

I The same output can be directed to a file

>> fid=fopen(’mydata.txt’, ’wt’);

>> fprintf(fid, ’%s\n’, ’% k sqrt(k)’);

>> for k=1:3

fprintf(fid, ’%d %6.3f\n’, k, sqrt(k));

end

>> fclose(fid);

I An easy way to load text data

>> load ’mydata.txt’

>> disp(mydata)

1.0000 1.0000

2.0000 1.4140

3.0000 1.7320