+ All Categories
Home > Documents > MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Date post: 21-Jan-2016
Category:
Upload: griselda-wendy-oconnor
View: 221 times
Download: 0 times
Share this document with a friend
29
MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland
Transcript
Page 1: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

MATLAB Programming

COMM2M

Harry R. Erwin, PhD

University of Sunderland

Page 2: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Sources

• James E. Gentle, 2002, Elements of Computational Statistics, Springer.

Page 3: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Topics

• Operators and Flow Control• M-Files• Functions• Input and Output• M-File Style• Optimization• Tutorial• Individual Project

Page 4: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Operators and Flow Control

• Relational and Logical Operators

• Flow Control

Page 5: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Relational Operators

• The six relational operators are:– == (equal)– ^= (not equal)– <– >– <=– >=

• True is 1 and false is 0• Comparisons involving matrices produce matrices.

Page 6: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Logical Functions

• ischar• isempty• isequal• isfinite• isieee• isinf

• islogical• isnan• isnumeric• isreal• issparse

Page 7: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Logical Operators

• & (logical and)• | (logical or)• ~ (logical not)• xor (logical exclusive or)• all (true if all elements of vector are

nonzero)• any (true if any element of vector is

nonzero)

Page 8: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Find

• The find() command returns the indices corresponding to the non-zero elements of a vector. Applied to a matrix M, it works with M(:).

• This can be used with any of these functions and operators.

• If f was generated by f = find(X), then X(f) are the non-zero elements of X.

Page 9: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

If Then Else

if expression (handled like C/C++/Java)

statements (comma separated on one line)

elseif expression2 (optional)

elseif statements

else (optional)

final set of statements

end

Page 10: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

For Loop

• Convenient (but avoid if performance-critical; use vectors instead)for variable = expression

for statements (, sep if 1 line)end

• Expression is usually i:s:j. It can be a matrix, in which case the columns from first to last are used.

Page 11: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

While Loop

while expressionstatements

end• As long as expression remains true (^==0)• for and while loops can be terminated with a

break.• continue jumps back to the loop start.• Infinite loop:

while 1, …, end

Page 12: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Switch Statement

switch expressioncase value1 statementscase value2 statementscase value3 statementsotherwise statements (optional)

end• The case value can be a value list within {…}

forming a cell array.• This is different from C!!!!!

Page 13: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

M-Files

• Scripts—no input or output arguments and operate on variables in the workspace

• Functions—contain a function definition line and can work with input and output arguments. Internal variables are local unless declared global.

Page 14: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Scripts

• Format for a script called spin.m:

%SPIN

% describes what it does

executable statements

Page 15: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Functions

function retval = name(arguments)%NAME one line description. (H1 line)% more details including argumentscode statements, eventually setting retval

• The name of the m-file should be the name of the function.

• The H1 line should omit ‘the’ and ‘a’. It should start with a capital letter and end with ‘.’.

• There is usually a blank line after the header.• The return command can be used to exit.

Page 16: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Editing M-Files

• M-files are ASCII files, so you can use any text editor.

• MATLAB has a built-in editor/debugger.– Type edit– Or use the menu in Windows systems.

• MATLAB maintains a search path to find M-files. Use the path and addpath commands. There is also a path browser that can be called by pathtool.

• Relevant commands available include what, lookfor, help, type, exist, and more.

Page 17: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Function Details

• Functions can be passed as argument to other functions. Such an argument is preceded by @, e.g., @fun. Handle it using feval.

• Functions can also be passed as name strings. This is not preferred.

• The vectorize() function can be used to convert multiplication, division, and exponentiation to array operations

Page 18: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Subfunctions

• Any M-file can contain local functions after the first one that can be called by the first one or other subfunctions.

• Usually you head a subfunction with% Subfunction

• Subfunctions can be arguments.• Functions and subfunctions can call

themselves recursively.

Page 19: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Input and Output

• User input

• Screen display

• Reading and writing text files

Page 20: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

User Input

• The input function will display a prompt and wait for user input. Input is interpreted as a string if input is called with a second argument ‘s’.

• The function ginput collects data via mouse click coordinates.

• The function pause() suspends execution until a key is clicked. pause(n) waits n seconds.

Page 21: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Screen Display

• If you don’t append a ‘;’ there will be output to the screen.

• The disp(var) function displays var.

• The fprintf function gives more sophisticated control.

• The sprintf function returns a string that fprintf would have printed.

Page 22: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Text Files

• Type help iofun for the list of functions that support text and binary file io.

• These are generally similar to C functions.

Page 23: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

M-File Style

• Be careful to fully document your files. In particular, provide an example of how the function can be used that can be cut and pasted.

• Space around logical operators and =• One statement per line• Indentation to emphasize structure.• Matrix names should be capitalized.

Page 24: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Optimization

• You may compile M-files.

• Vectorize, don’t shade your eyes:

n = 5e5; x = randn(n,1);

tic, s = 0; for i=1:n, s = s+x(i)^2; end, toc

Elapsed time = 8.35

tic, s = sum(x.^2); toc

Elapsed time = 0.06

Page 25: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

More Optimization

• Preallocate large arrays. Otherwise they may be expanded one row/column at a time.

• The repmat function is much faster than anything that involves manipulating individual matrix entries.

• Empty arrays/matrices are handled by extrapolating operations on non-empty ones. This may be very convenient.

Page 26: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Grand Tour Tutorial

• When a cluster of data points is rotated, patterns in the data may become apparent.

• Rotations are orthogonal transformations that preserve the norms of the data vectors and the angles between.

• Simple rotation matrices start with the identity matrix and change the four elements aii, aij, aji, and ajj. aii and ajj are replaced with cos(), aij becomes sin(), and aji becomes -sin().

Page 27: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Generalized Rotation Matrices

• A generalized rotation matrix, Q, is the product of (d2-d)/2 such simple rotation matrices.

Q = Q12Q13…Q1dQ23Q24

…Q2d…Qd-1,d

Page 28: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Constructing the Plot

• Rotating a plot in all directions, and projecting into the first two or three dimensions is called a “Grand Tour” (Asimov 1985).

• You can take for the values of ij,

tij modulo 2where the ij are linearly independent over the integers. Suitable constants are the square roots of the first (d2-d)/2 primes.

• Plot the first two (or three) dimensions.• Suitable data can be found here: <http://lib.stat.cmu.edu/>• Step time and observe the changes.

Page 29: MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.

Suitable Data Can Be Found At:

• <http://lib.stat.cmu.edu/>


Recommended