Introduction to MATLAB Programming Ian Brooks Institute for Climate

52 Slides1.44 MB

Introduction to MATLAB Programming Ian Brooks Institute for Climate & Atmospheric Science School of Earth & Environment [email protected]

Course Resources Course web page: http://homepages.see.leeds.ac.uk/ lecimb/matlab/index.html Course power point slides Exercises

What is MATLAB? Data processing and visualization tools – Easy, fast manipulation and processing of complex data – Visualization to aid data interpretation – Production of publication quality figures High-level programming languages – Can write extensive programs, applications, – Faster code development than with C, Fortran, etc. – Possible to “play” with or “explore” data – don’t have to write a standalone program to do a predetermined job

Getting Started: Windows

Getting started – linux (SEE) Just enter ‘matlab’ or ‘matlab &’ on the command line Might need to run ‘app setup matlab’ or add this to your .cshrc file

MATLAB User Environment Workspace/Variable Inspector Command Window Command History

Getting help There are several ways of getting help: Basic help on named commands/functions is echoed to the command window by: help command-name A complete help system containing full text of manuals is started by: helpdesk

Accessing the Help Browser via the Start Menu

Help Browser Contents Search Index Demos Contents - browse through topics in an expandable "tree view" Index - find topics using keywords Search - search the documentation. There are four search types available: Full Text - perform a full-text search of the documentation Document Titles - search for word(s) in documentation section titles Function Name - see reference descriptions of functions Online Knowledge Base - search the Technical Support Knowledge Base Demos – view and run product demos

Other sources of help www.mathworks.com – Help forums, archived questions & answers, archive of user-submitted code http://lists.leeds.ac.uk/mailman/listinfo/see-matlab – Mailing list for School of Earth & Environment self-help from other users within the school (31 at last count)

Modifying the MATLAB Desktop Appearance

Returning to the Default MATLAB Desktop

The Contents of the MATLAB Desktop

Workspace Browser

Array Editor double-click For editing 2-D numeric arrays

Command History Window

Current Directory Window

Calculations on the command Line MATLAB as a calculator Assigning Variables -5/(4.8 5.32) 2 -5/(4.8 5.32) 2 ans ans -0.048821 -0.048821 aa 2; 2; AA 5; 5; a A a A ans ans 32 32 xx 5/2*pi; 5/2*pi; yy sin(x) sin(x) yy 11 zz asin(y) asin(y) zz 1.5708 1.5708 (3 4i)*(3-4i) (3 4i)*(3-4i) ans ans 25 25 cos(pi/2) cos(pi/2) ans ans 6.1232e-017 6.1232e-017 exp(acos(0.3)) exp(acos(0.3)) ans ans 3.547 3.547 Semicolon suppresses screen output Variables are case sensitive Results assigned to “ans” if name not given Use parentheses ( ) for function inputs Numbers stored in double-precision floating point format

The WORKSPACE MATLAB maintains an active workspace, any variables (data) loaded or defined here are always available. Some commands to examine workspace, move around, etc: who : lists the variables defined in workspace who Your variables are: x y

whos : lists names and basic properties of variables in the workspace whos Name x y Size 3x1 3x2 Bytes 24 48 Grand total is 9 elements using 72 bytes Class double array double array

Entering Numeric Arrays Row separator: Semicolon (;) or newline Column separator: space or comma (,) Creating sequences using the colon operator (:) Utility function for creating matrices. a [1 a [1 2;3 2;3 4] 4] aa 11 22 33 44 Use square brackets [ ] bb [2:-0.5:0] [2:-0.5:0] bb 22 1.5 11 1.5 0.5 0.5 cc rand(2,4) rand(2,4) cc 0.9501 0.9501 0.6068 0.6068 0.2311 0.2311 0.4860 0.4860 0.4565 0.4565 0.0185 0.0185 0.8913 0.8913 0.7621 0.7621 Matrices must be rectangular. (Undefined elements set to zero) 00

Entering Numeric Arrays (Continued) Using other MATLAB expressions Matrix element assignment Adding to an existing array ww [-2.8, [-2.8, sqrt(-7), sqrt(-7), (3 5 6)*3/4] (3 5 6)*3/4] ww -2.8 00 2.6458i 10.5 -2.8 2.6458i 10.5 m(3,2) m(3,2) 3.5 3.5 mm 00 00 00 00 00 3.5 3.5 w(2,5) w(2,5) 23 23 ww -2.8 -2.8 00 2.6458i 2.6458i 00 00 10.5 10.5 00 00 00 00 23 23 Note: MATLAB deals with Imaginary numbers

Indexing into a Matrix in MATLAB Columns (n) 2 3 4 1 A 6 1 11 6 16 1.2 7 9 12 4 17 25 22 7.2 3 5 8 7 13 1 18 11 23 4 0 4 0.5 9 4 14 5 19 56 24 5 23 5 13 15 0 20 10 1 2 Rows (m) 3 4 1 8 2 5 10 83 10 2 21 25 A (2,4) A (17) Rectangular Matrix: Scalar: 1-by-1 array Vector: m-by-1 array 1-by-n array Matrix: m-by-n array

Array Subscripting / Indexing 1 A A(3,1) A(3) 4 1 2 8 2 3 7.2 3 4 0 4 5 23 5 1 2 3 4 5 6 1 11 6 16 1.2 7 9 12 4 17 5 8 7 13 1 18 11 23 0.5 9 4 14 5 19 56 24 13 15 0 20 10 10 83 10 2 21 25 22 A(1:5,5) A(1:end,end) A(:,5) A(:,end) A(21:25) A(21:end)’ 25 Use () parentheses to specify index colon operator (:) specifies range / ALL [ ] to create matrix of index subscripts 'end' specifies maximum index value A(4:5,2:3) A([9 14;10 15])

THE COLON OPERATOR Colon operator occurs in several forms – NTo indicate 5:10:35 a range (as above) N – To indicate a range with non-unit increment 5 15 25 35 P [1:3; 30:-10:10] P 1 2 3 30 20 10

ToAextract ALL the elements of an array [1:3; 10:10:30; A(:) (extracts everything to aanssingle column 100:100:300] 1 Avector) 10 1 2 3 10 20 30 100 200 300 100 2 20 200 3 30 300

Numerical Array Concatenation [ ] Use [ ] to combine existing arrays as matrix “elements” Row separator: semicolon (;) Column separator: space / comma (,) N.B. Matrices MUST be rectangular. a [1 a [1 2;3 2;3 4] 4] Use square aa brackets [ ] 11 22 33 44 cat a [a, cat a [a, 2*a; 2*a; 3*a, 3*a, 4*a; 4*a; 5*a, 5*a, 6*a] 6*a] cat a cat a 11 22 22 44 33 44 66 88 33 66 44 88 4*a 99 12 12 16 12 12 16 55 10 66 12 10 12 15 20 18 24 15 20 18 24

Matrix and Array Operators Matrix Operators Array operators () parentheses Common Matrix Functions ' complex conjugate .' array transpose transpose power . array power inv matrix inverse det determinant rank matrix rank * multiplication .* array mult. eig / division ./ array division svd eigenvectors and eigenvalues singular value dec. norm matrix / vector norm \ left division addition - subtraction help ops help matfun

1 & 2D arrays are treated as formal 1x2 row oriented array (vector) a [1 2]; (Trailing semicolon suppresses display of output) matrices b [3 4]; – Matrix algebra works by default: 2x1 column oriented array a*b ans 11 Result of matrix multiplication depends on order of terms (non-cummutative) b*a ans 3 6 4 8

Element-by-element (array) operation is a [1 2]; forced b [3 by preceding operator with a period 4]; ‘.’c [3 4]; a.*b ? Error using times Matrix dimensions must agree. a.*c ans 3 8 Size and shape must match

Matrix Calculation-Scalar Expansion w [1 w [1 2;3 2;3 4] 4] 55 ww 66 77 88 99 w [1 w [1 2;3 2;3 4] 4] 55 11 22 33 44 11 22 33 44 66 77 88 99 55 Scalar expansion 55 55 55 55

Matrix Multiplication Inner dimensions must be equal. Dimension of resulting matrix outermost dimensions of multiplied matrices. Resulting elements dot product of the rows of the 1st matrix with the columns of the 2nd matrix. aa [1 [1 22 3;4 3;4 55 6]; 6]; bb [3,1;2,4;-1,2]; [3,1;2,4;-1,2]; [2x3]*[3x2] cc a*b a*b cc 44 15 15 16 36 16 36 a(2nd row).b(2nd column) [2x3] [3x2] [2x2]

Array (element-by-element) Multiplication Matrices must have the same dimensions (size and shape) Dimensions of resulting matrix dimensions of multiplied matrices aa [1 [1 22 33 4; 4; 55 66 77 8]; 8]; Resulting elements product of corresponding elements from the b [1:4; 1:4]; b [1:4; 1:4]; original matrices c a.*b c a.*b cc 11 44 55 12 12 99 21 21 16 16 32 32 c(2,4) a(2,4)*b(2,4) Same rules apply for other array operations

a [1 2] A 1 2 No trailing semicolon, immediate display of result b [3 4]; a.*b ans 3 8 c a b c 4 6 Element-by-element multiplication Matrix addition & subtraction operate element-by-element anyway. Dimensions of matrix must still match!

A [1:3;4:6;7:9] A 1 2 3 4 5 6 7 8 9 mean(A) ans 4 5 6 sum(A) ans 12 18 15 mean(A(:)) ans 5 Many common functions operate on columns by default Mean of each column in A Mean of all elements in A

Clearing up clear clear all workspace clear VARNAME clear named variable clear all clear everything (see help clear) close all close all figures clc clears command window display only

Boolean (logical) operators & is equal to greater than less than greater than or equal to less than or equal to not and or isempty() true if matrix is empty, [] isfinite() true where elements are finite isinf() true where elements are infinite any() true if any element is nonzero all() true is all elements are non-zero zeros([m,n]) - create an m-by-n matrix of zeros zeros(size(A)) - create a matrix of zeros the same size as A

LOGICAL INDEXING Instead of indexing arrays directly, a logical mask can be used – an array of same size, but consisting of 1s and 0s (true and false) – usually derived as result of a logical expression. X [1:10] X 1 2 3 ii X 6 ii 0 0 4 5 6 7 8 9 10 0 0 0 0 1 1 1 1 9 10 X(ii) ans 7 8

Logical indexing is a very powerful tool for selecting subsets of data. Combine multiple conditions using boolean operators.

x [1:10]; y x. 0.5; i1 x 5 I1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 0 0 i2 y 3 i2 1 1 ii i1 & i2 ii 0 0 find(ii) ans 5 Find function converts logical index to numeric index 6 7 8

plot(x,y,’bo’) plot(x(ii),y(ii),’ro’)

Basic Plotting Commands figure plot(x) : creates a new figure window : plots line graph of x vs index number of array plot(x,y) : plots line graph of x vs y plot(x,y,'r--') : plots x vs y with linetype specified in string : 'r' red, 'g' green, etc for a limited set of basic colours. ' ' solid line, ' ' dashed, 'o' circles see graphics section of helpdesk

Simple Plotting x [1:10]; y x. 2; plot(x,y) plot(x,y,'--') plot(x,y,‘r-') plot(x,t,‘o') Specify simple line types, colours, or symbols Use the help command to get guidance on using another command or function help plot

By default any plotting command replaces any existing lines plotted in current figure. hold command ‘holds’ the current plotting axes so that subsequent plotting commands add to the existing figure instead of replacing content.

Back to top button