Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland."— 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 Logical Functions ischar isempty isequal isfinite isieee isinf islogical isnan isnumeric isreal issparse

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) %NAMEone 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 a ii, a ij, a ji, and a jj. a ii and a jj are replaced with cos(  ), a ij becomes sin(  ), and a ji becomes -sin(  ).

27 Generalized Rotation Matrices A generalized rotation matrix, Q, is the product of (d 2 -d)/2 such simple rotation matrices. Q = Q 12 Q 13 … Q 1d Q 23 Q 24 … Q 2d … Q d-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  ij are linearly independent over the integers. Suitable constants are the square roots of the first (d 2 -d)/2 primes. Plot the first two (or three) dimensions. Suitable data can be found here: Step time and observe the changes.

29 Suitable Data Can Be Found At:


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

Similar presentations


Ads by Google