1 / 29

MATLAB Programming

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.

Télécharger la présentation

MATLAB Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

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

  4. Operators and Flow Control • Relational and Logical Operators • Flow Control

  5. Relational Operators • The six relational operators are: • == (equal) • ^= (not equal) • < • > • <= • >= • True is 1 and false is 0 • Comparisons involving matrices produce matrices.

  6. ischar isempty isequal isfinite isieee isinf islogical isnan isnumeric isreal issparse Logical Functions

  7. 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)

  8. 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.

  9. 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

  10. 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.

  11. While Loop while expression statements 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

  12. Switch Statement switch expression case value1 statements case value2 statements case value3 statements otherwise statements (optional) end • The case value can be a value list within {…} forming a cell array. • This is different from C!!!!!

  13. 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.

  14. Scripts • Format for a script called spin.m: %SPIN % describes what it does executable statements

  15. Functions function retval = name(arguments) %NAME one line description. (H1 line) % more details including arguments code 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.

  16. 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.

  17. 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

  18. 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.

  19. Input and Output • User input • Screen display • Reading and writing text files

  20. 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.

  21. 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.

  22. Text Files • Type help iofun for the list of functions that support text and binary file io. • These are generally similar to C functions.

  23. 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.

  24. 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

  25. 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.

  26. 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. aiiand ajjare replaced with cos(),aijbecomes sin(), and ajibecomes -sin().

  27. 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

  28. 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, tij modulo 2 where the ijare 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.

  29. Suitable Data Can Be Found At: • <http://lib.stat.cmu.edu/>

More Related