Refactoring to Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.
-
Upload
griselda-wendy-oconnor -
Category
Documents
-
view
221 -
download
0
Transcript of MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.
MATLAB Programming
COMM2M
Harry R. Erwin, PhD
University of Sunderland
Sources
• James E. Gentle, 2002, Elements of Computational Statistics, Springer.
Topics
• Operators and Flow Control• M-Files• Functions• Input and Output• M-File Style• Optimization• Tutorial• Individual Project
Operators and Flow Control
• Relational and Logical Operators
• Flow Control
Relational Operators
• The six relational operators are:– == (equal)– ^= (not equal)– <– >– <=– >=
• True is 1 and false is 0• Comparisons involving matrices produce matrices.
Logical Functions
• ischar• isempty• isequal• isfinite• isieee• isinf
• islogical• isnan• isnumeric• isreal• issparse
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)
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.
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
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.
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
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!!!!!
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.
Scripts
• Format for a script called spin.m:
%SPIN
% describes what it does
executable statements
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.
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.
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
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.
Input and Output
• User input
• Screen display
• Reading and writing text files
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.
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.
Text Files
• Type help iofun for the list of functions that support text and binary file io.
• These are generally similar to C functions.
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.
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
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.
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().
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
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.
Suitable Data Can Be Found At:
• <http://lib.stat.cmu.edu/>