AOS Linux Tutorial Matlab Michael Havas Dept. of Atmospheric and - - PowerPoint PPT Presentation

aos linux tutorial
SMART_READER_LITE
LIVE PREVIEW

AOS Linux Tutorial Matlab Michael Havas Dept. of Atmospheric and - - PowerPoint PPT Presentation

AOS Linux Tutorial Matlab Michael Havas Dept. of Atmospheric and Oceanic Sciences McGill University October 19, 2010 Outline 1 Introduction 2 Matlab basics Built-in functions Vectors Matrices Saving and Loading 3 Plotting 4 Systems of


slide-1
SLIDE 1

AOS Linux Tutorial

Matlab Michael Havas

  • Dept. of Atmospheric and Oceanic Sciences

McGill University October 19, 2010

slide-2
SLIDE 2

Outline

1 Introduction 2 Matlab basics

Built-in functions Vectors Matrices Saving and Loading

3 Plotting 4 Systems of Linear Equations 5 Matlab scripts 6 Next time

slide-3
SLIDE 3

Matlab History

Matlab History Created in the late 1970’s by Cleve Moler. Designed to give students access to LINPACK and EISPACK without having to learn fortran. Rewritten and released by Mathworks in 1984 under a commercial license.

slide-4
SLIDE 4

What is Matlab and what is it good for?

What’s Matlab? Is a numerical computing environment and programming language. Although concentrated on numerical computing, symbolic computing is possible. What’s it good for Matrix manipulations. Plotting of functions and data. Implementation of algorithms. Creation of user interfaces. Interfacing with programs written in other languages including C, C++ and Fortran.

slide-5
SLIDE 5

Matlab tutorial

Credit where credit is due

Credit The majority (ALL) of this tutorial is taken from: http://www.maths.dundee.ac.uk/~ftp/na-reports/ MatlabNotes.pdf Much thanks to Dundee University for providing such a great tutorial to the public.

slide-6
SLIDE 6

Outline

1 Introduction 2 Matlab basics

Built-in functions Vectors Matrices Saving and Loading

3 Plotting 4 Systems of Linear Equations 5 Matlab scripts 6 Next time

slide-7
SLIDE 7

Matlab basics

Matlab as a calculator

Operators and order of operations () Parentheses. ˆ Exponent. *, / Multiplication and division. +, - Addition and subtraction. Example

>> 2 + 3 / 4 ∗ 5 ans = 5.7500 >>

slide-8
SLIDE 8

Matlab basics

Numbers

Kinds of numbers Matlab recognizes several different kinds of numbers: Type Examples Integer 1362, 217897 Real 1.234, -10.76 Complex 3.21 - 4.3i Inf Infinity NaN Not a Number, 0/0 “e” Notation −1.3412e + 03 = −1.3412 × 103 Note Matlab does all operations in double-precision.

slide-9
SLIDE 9

Matlab basics

Formats

The format command The format command controls how Matlab prints numbers. Some examples; Command Example of Output >>format short 31.4162 >>format short -e 3.1416e+01 >>forat long e 3.141952653589793e+01 >>format blank 31.42 Note Matlab does all operations in double-precision.

slide-10
SLIDE 10

Matlab basics

Variables

Predefined variables The variable ans is a predefined variable defined as the answer to the previous query. For example:

>> 3 − 2ˆ4 ans = −13 >> ans ∗ 5 ans = −65

Defining variables We can use our own names to define variables. Variable names must begin with a letter and contain only letters and numbers.

>> x = 3 − 2ˆ4 x = −13 >> y = x∗5 y = −65

Avoid using reserved words like pi, sin, . . .

slide-11
SLIDE 11

Matlab basics

Suppressing output

Suppressing output To suppress output of a given expression, simply append a ;. For example:

>> x = 13; >> y = 5∗x , z=xˆ2+y y = −65 z = 104 >>

slide-12
SLIDE 12

Matlab basics

Elementary and trigonometric functions

Trigonometric functions Matlab knows sin, cos and tan and their inverse asin, acos and

  • atan. These functions expect paramters in radians. For example:

>> x = 5 ∗ cos ( pi /6) , y=5∗ s i n ( pi /6) x = 4.3301 y = 2.500 >> acos ( x /5) , asin ( y ) x = 0.5236 y = 0.5236 >> pi /6 ans = 0.5236

Elementary functions These include sqrt, exp, log, log10.

slide-13
SLIDE 13

Matlab basics

Vectors

Row vectors Row vectors are written [1 2 3 4] and can be arbitrarily large. Be careful with spaces [1+ 2 3 4] is not equal to [1 +2 3 4]. Suggest using commas between values. Can use operators in vector assignment:

[ sin(pi ), cos(pi ), tan(pi ), 17].

Column vectors Column vectors are written [1; 2; 3] or

>> [ 1 2 3]

Can be arbitrarily large. Can use operators in vector assignment.

slide-14
SLIDE 14

Matlab basics

Vectors

Getting and setting elements in a vector Use the () operator. For example,

>> v1 =[1 ,2 ,3]; v2 = [ 4 ; 5 ; 6 ] ; >> v1 (2) ans = 2 >> v2 (2) ans = 5 >> v2 (2) = 17 v2 = 4 17 6 >>

slide-15
SLIDE 15

Matlab basics

Vectors

Colon notation Is used as a shortcut to creating row vectors. Generally, a : b : c, produces a row vector of entries starting at a, incrementing by the value b until it gets to c. Transposing We can convert a row vector to a column vector using the transpose operator ’. For example:

>> v = 1:2 v = 1 2 >> v ’ ans = 1 2

Note that if v is complex, then ’ returns the complex conjugate

  • transpose. .’ will return the regular transpose.
slide-16
SLIDE 16

Matlab basics

Vectors

Vector operators and functions Name Symbol Example Vector addition + [1, 2, 3] + [4, 5, 6] Vector subtraction

  • [1, 2, 3] − [4, 5, 6]

Scalar multiplication * 10 ∗ [1, 2, 3] Vector concatenation [ ] [[1, 2, 3], [4, 5, 6]] Vector sorting sort() sort([3, 2, 1]) Vector multiplication * [1, 2, 3] ∗ [1; 2; 3] Vector dot product .* [1, 2, 3]. ∗ [1, 2, 3] Vector dot division ./ [1, 2, 3]./[1, 2, 3] Vector dot power .^ [1, 2, 3].ˆ[1, 2, 3] Vector length length() length([1, 2, 3])

slide-17
SLIDE 17

Matlab basics

Matrices

Syntax The matrix A = 1 2 3 4 5 6

  • can be defined in Matlab as:

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

slide-18
SLIDE 18

Matlab basics

Matrices

size of a matrix The size of a matrix can be computed using the size function. It returns a row vector of length two with the first element being the number of rows in the matrix and the second element being the number of columns. For example,

>> [ numRows , numCols ] = s i z e (A) numRows = 2 numCols = 3

Transposing a matrix The transpose of a matrix is done using the ’ operator. For example:

>> A’ ans = 1 4 2 5 3 6

slide-19
SLIDE 19

Matlab basics

Matrices

Special matrices

  • nes(m, n) An m × n matrix of ones.

zeros(m, n) An m × n matrix of zeros. eye(n) The n × n identity matrix. diag(⌊d1, . . . , dn⌋) A diagonal n × n matrix with elements d1, d2, . . . , dn along the diagonal. diag(A) also returns the diagonal elements of a matrix An×n

slide-20
SLIDE 20

Matlab basics

Matrices

Constructing Matrices It is often convenient to build matrices from smaller ones. For example:

>> C=[0 1; 3 −2; 4 2 ] ; x =[8; −4;1]; >> G = [C x ] G = 1 8 3 −2 −4 4 2 1 >> J = [ 1 : 4 ; 5 : 8 ; 9 : 1 2 ; 20 0 5 4 ] ; >> K = [ diag ( 1 : 4 ) J ; J ’ zeros ( 4 , 4 ) ] K = 1 1 2 3 4 2 5 6 7 8 3 9 10 11 12 4 20 5 4 1 5 9 20 2 6 10 3 7 11 5 4 8 12 4

slide-21
SLIDE 21

Matlab basics

Matrices

Extracting an element from a matrix To extract an element from a matrix, you use A(i, j) where A is a matrix, i is the row you are interested in and j is the column. Extracting more than just an element A(:, j) Extracts the j’th column. A(:, j1 : j2) Extracts the j1’th to the j2’th columns. A(i, :) Extracts the i’th column. A(i1 : i2; j1 : j2) Extracts the region defined by rows i1 to i2 and colmns j1 and j2

slide-22
SLIDE 22

Matlab basics

Matrices

Sparse matrices Matlab defines a sparse matrix using three vectors: i A vector of length n defining the row indices of non-zero elements. j A vector of length n defining the colunn indices of non-zero elements v A vector of length n defining the values at each index defined by i and j. Example For example, we can represent A =       10 11 12       as:

>> i = [1 , 3 , 5 ] ; >> j = [ 2 , 3 , 4 ] ; >> v = [10 11 1 2 ] ; >> S = sparse ( i , j , v ) S = (1 ,2) 10 (3 ,3) 11 (5 ,4) 12

slide-23
SLIDE 23

Matlab basics

Matrices

Matrix operations Name Symbol Example Matrix addition + [1, 2; 3, 4] + [5, 6; 7, 8] Matrix subtraction

  • [1, 2; 3, 4] − [5, 6; 7, 8]

Scalar multiplication * 10 ∗ [1, 2; 3, 4] Matrix multiplication * [1, 2; 3, 4; 5, 6] ∗ [1, 2, 3; 4, 5, 6] Matrix norm norm() norm([1, 2; 3, 4])

slide-24
SLIDE 24

Matlab basics

Saving and Loading

Saving and loading Keep a diary of everything you type by issuing diary filename.txt Turn off and on using diary off and diary on respectively. Save your session by issuing: save thisSession where thissession is a filename. Load your session by issuing: load savedSession where savedSession is a previously saved session. See which variables are in use by using the whos command.

slide-25
SLIDE 25

Outline

1 Introduction 2 Matlab basics

Built-in functions Vectors Matrices Saving and Loading

3 Plotting 4 Systems of Linear Equations 5 Matlab scripts 6 Next time

slide-26
SLIDE 26

Plotting

Plotting elementary functions

An example Say we want to plot y = sin(3πx) for 0 ≤ x ≤ 1. We do this by sampling the function for a sufficiently large number of points and joining these points with lines. Say we want to have the points evenly separated. For N number of points, we then have vector >> N=100; x = 0:1/N:1;. We can then say >> y = sin(3 ∗ pi ∗ x). Now that we have x and y vectors, we can plot them using

>> plot(x,y).

slide-27
SLIDE 27

Plotting

Customization

Making things pretty title() Sets the title of the plot. xlabel() Sets the x-axis label of the plot. ylabel() Sets the y-axis label of the plot. grid Turns the grid on and off. Line styles and colour Colours Line Styles y yellow . point m magenta

  • circle

c cyan x x-mark r red + plus g green

  • solid

b blue * star w white : dotted k black

  • .

dash-dot

slide-28
SLIDE 28

Plotting

Multi-Plots

Simple Multi-Plots Several plots may be drawn on the same figure using:

>> plot ( x , y , w − , x , cos (3∗ pi ∗x ) , g − − )

A descriptive legend may be included using the legend command. For example:

>> legend ( ’sin curve’ , ’cos curve’)

Multi-Plots and Holding It is often desirable to multi-plot using several plot statements. To do this, use the hold command:

>> plot ( x , y , ’w-’ ) ; hold on >> plot ( x , cos (3∗ pi ∗x ) , ’g--’ ) ; hold

  • f f
slide-29
SLIDE 29

Plotting

Subplots

Subplots Figures may be split into an m × n grid of smaller windows into which we may plot one or more figures. The figures are counted 1, 2, . . . , m × n starting from top-left. For example:

>> subplot (2 ,2 ,1) , plot ( x , y ) >> x l a b e l ( x ) , y l a b e l ( s i n 3 pi x ) >> subplot (2 ,2 ,2) , plot ( x , cos (3∗ pi ∗x )) >> x l a b e l ( x ) , y l a b e l ( c o s 3 pi x ) >> subplot (2 ,2 ,3) , plot ( x , s i n (6∗ pi ∗x )) >> x l a b e l ( x ) , y l a b e l ( s i n 6 pi x ) >> subplot (2 ,2 ,4) , plot ( x , cos (6∗ pi ∗x )) >> x l a b e l ( x ) , y l a b e l ( c o s 6 pi x )

Note that subplot(2,2,1) specifies that the window should be split into a 2 × 2 grid and we select the first window.

slide-30
SLIDE 30

Plotting

Surface plots

Mesh, surf, surfl and contour plots: An example Plot the surface defined by f (x, y) = (x − 3)2 − y2)2 for 2 ≤ x ≤ 4 and 1 ≤ y ≤ 3.

>> [X,Y] = meshgrid ( 2 : . 2 : 4 , 1 : . 2 : 3 ) ; >> Z = (X−3).ˆ2−(Y−2).ˆ2; >> mesh(X,Y, Z) >> s u r f (X,Y, Z) >> s u r f l (X,Y, Z) >> contour (X,Y, Z)

slide-31
SLIDE 31

Outline

1 Introduction 2 Matlab basics

Built-in functions Vectors Matrices Saving and Loading

3 Plotting 4 Systems of Linear Equations 5 Matlab scripts 6 Next time

slide-32
SLIDE 32

Systems of linear equations

Introduction

Introduction A system of linear equations is a set of equations a1,1x1 + a1,2x2 + · · · a1,nxn = b1 a2,1x1 + a2,2x2 + · · · a2,nxn = b2 . . . = . . . an,1x1 + an,2x2 + · · · an,nxn = bn This can be represented in matrix form as Ax = b. Solving in Matlab In Matlab, we use the \ operator to solve for such systems. For example:

>> x = A \ b

slide-33
SLIDE 33

Outline

1 Introduction 2 Matlab basics

Built-in functions Vectors Matrices Saving and Loading

3 Plotting 4 Systems of Linear Equations 5 Matlab scripts 6 Next time

slide-34
SLIDE 34

Matlab scripts

Simple scripts

Simple scripts Matlab scripts are text files ending in .m. They are just sets of instructions for Matlab. Only the output of the script is shown and not the commands themselves by default. Turn on viewing the commands by issuing echo on at the top

  • f your script.

Comments begin with %.

slide-35
SLIDE 35

Matlab scripts

Function m-files

Function m-files Defines a function, its parameters and its operations in one file. Ensure the name of your function does not conflict with a built-in Matlab function. The first line of the file must have the format:

function [ outputs ] = function name ( i n p u t s )

Make sure you document your function with comments.

slide-36
SLIDE 36

Matlab scripts

Function m-files

An example

function [A] = area ( a , b , c ) % Compute the area

  • f

a t r i a n g l e % I n p ut s : a , b , c : Lengths

  • f

s i d e s % Output : A: area

  • f

t r i a n g l e % Usage : % Area = area ( 2 , 3 , 4 ) ; % Written by dfg , Oct 14 , 1996. s = ( a+b+c ) / 2 ; A = sqrt ( s ∗( s−a )∗( s−b )∗( s−c ) ) ; % % % % % % % % % end

  • f

area % % % % % % % % % % %

Calling the function

>> help area % Produces the l e a d i n g comment from the f i l e . >> Area = area (10 ,15 ,20) Area = 72.6184

slide-37
SLIDE 37

Matlab scripts

Control structures

For-loop example (Fibonacci)

% Shows that F {n−1}/ f n −> (\ s q r t {5} − 1)/2 ( golden r a t i o ) >> F(1)=0; F(2)=1; >> for i = 3:20 F( i ) = F( i −1) + F( i −2); end >> plot (1:19 , F ( 1 : 1 9 ) . / F ( 2 : 2 0 ) , ’o’) >> hold on , x l a b e l ( ’n’) >> plot (1:19 , F ( 1 : 1 9 ) . / F ( 2 : 2 0 ) , ’-’) >> legend ( ’Ration of terms f_{n-1}/f_n’) >> plot ( [ 0 20] , sqrt (5) −1/2∗[1 ,1] , ’--’)

slide-38
SLIDE 38

Matlab scripts

Control structures

Logicals == True if a = b = True if a = b > True if a > b < True if a < b >= True if a ≥ b <= True if a ≤ b Conditionals

>> i f a >= c b = sqrt ( aˆ2 − c ˆ2) e l s e i f aˆc > cˆa b = cˆa/aˆc e l s e b = aˆc/cˆa end

slide-39
SLIDE 39

Matlab scripts

Control structures

While-Loops

while [ a l o g i c a l t e s t ] commands to be executed when c o n d i t i o n i s t r u e end

slide-40
SLIDE 40

Matlab scripts

Example functions

Fib1.m

function f = Fib1 ( n ) % Returns the nth number i n % the Fibonacci sequence . F=zeros (1 , n+1); F(2) = 1; for i = 3: n+ F( i ) = F( i −1) + F( i −2); end f = F( n ) ;

Fib2.m

function f = Fib2 ( n ) % Returns the nth number i n % the Fibonacci sequence . i f n==1 f = 0; e l s e i f n==2 f = 1; e l s e f1 = 0; f2 = 1; for i = 2: n−1 f = f1 + f2 ; f1=f2 ; f2 = f ; end end

slide-41
SLIDE 41

Matlab scripts

Example functions

Fib3.m

function f = Fib3 ( n ) % Returns the nth number i n % the Fibonacci sequence . i f n==1 f = 0; e l s e i f n==2 f = 1; e l s e f = Fib3 (n−1) + Fib3 (n −2); end

Fib4.m

function f = Fib4 ( n ) % Returns the nth number i n % the Fibonacci sequence . A = [0 1;1 1 ] ; y = Aˆn ∗ [ 1 ; 0 ] ; f=y ( 1 ) ;

slide-42
SLIDE 42

Outline

1 Introduction 2 Matlab basics

Built-in functions Vectors Matrices Saving and Loading

3 Plotting 4 Systems of Linear Equations 5 Matlab scripts 6 Next time

slide-43
SLIDE 43

Next time

Open to suggestions. I’ve ran out of things to say...