Programming With MATLAB: Clodomiro Ferreira Aleksei Netsunajev EUI
Programming With MATLAB: Clodomiro Ferreira Aleksei Netsunajev EUI
1 / 75
Preliminaries (I)
MATLAB knowledge we assume: very basic - basic operations and matrix manipulation, feeling confortable with the main MATLAB windows... Objective of the tutorial: Allowing you to feel confortable when solving computational and numerical problems in MATLAB
2 / 75
Preliminaries (II)
3 / 75
Tentative Outline
1
Before we begin M-les, Scripts and Functions Control of Flow: if, for, while, ... Programming: general issues Graphics in MATLAB MATLAB Help Applications
MATLAB Tutorial 2011 February 10, 2011 4 / 75
Working environment
6 / 75
Working environment
7 / 75
M = [1, 2; 3, 4; 5, 6] is a 3x2 matrix 1 2 M= 3 4 5 6 M = [low : step : high] creates a row vector with rst element low, last element high and distance between elements step M = linspace(0,1,5) creates a row vector with 5 elements M = (0, 0.25, 0.5, 0.75, 1) Remember: use the semi-colon ";" after a command in order to tell MATLAB not to show output on the Command window.
Ferreira, C. and A. Netsunajev () MATLAB Tutorial 2011 February 10, 2011 10 / 75
1 2 M= 3 4 5 6 Accessing element (i, j): M (i, j). Type b = M (1, 2) b=2 Accessing row i: M (i, :) Accessing a particular range: M (i1 : i2 , j1 : j2 )
11 / 75
N1 N2 matrix of ones: ones(N1 , N2 ) N1 N2 matrix of zeros: zeros(N1 , N2 ) N1 N2 identity matrix : eye(N1 , N2 ) If M is an n m matrix, many common operations are available as MATLAB commands: inv(), det(), eig() Useful 1: MATLAB allows you to work on an "element by element" basis. Just add a "dot" n front of the operator: 1 4 M. M = 9 16 25 36 Useful 2: Multidimensional arrays. MATLAB allows you to create arrays with more than two dimensions. For example, A=zeros(2,2,3) creates a "cube" formed by three 2 2 arrays.
Ferreira, C. and A. Netsunajev () MATLAB Tutorial 2011 February 10, 2011 12 / 75
14 / 75
Save it on the current directory (cd). "call it": type on the Command Window clodo (or run clodo)
Variables and output created when running the .m le will be stored on the Workspace.
Ferreira, C. and A. Netsunajev () MATLAB Tutorial 2011 February 10, 2011 15 / 75
This program generates pseudo-random sequence of 0 and 1 clc clear all L = 10 ; x = rand(1,L) ; y = round(x) ; z = sum(y,2) ; y z
17 / 75
18 / 75
Functions: .m les that can accept imput arguments and return output arguments.
Built-in: functions already existing in MATLAB. Example: inv(.), regress(.), plot(.), etc. Own functions: functions created by you
20 / 75
21 / 75
More useful functions... Two things to note: 1 Imput arguments (X , y ), can have dierent dimensions 2 A function can have one or more imput arguments (with a maximum) and one or more output arguments. 1 2
b=regress(y,X) [b,bint,r,rint,stats]=regress(y,X)
22 / 75
Own Functions
Useful when we want to automatize a particular set of operations which require imput arguments from another set of operations.
General structure:
function f = myfun(x,y, ...) commands ... f = expression; or with more output arguments function [f1,f2] = myfun(x,y, ...) commands ... f1 = expression; f2 = expression;
Ferreira, C. and A. Netsunajev () MATLAB Tutorial 2011 February 10, 2011 23 / 75
24 / 75
Then, if we type in the Command Window (or we call it from another .m le) funct1(1,2) we get ans = 9.8660
Ferreira, C. and A. Netsunajev () MATLAB Tutorial 2011 February 10, 2011 25 / 75
More remarks: The name of the imputs, x and y, are only valid within the function. Usually, such imputs come fro previous calculations or parameters dened within a "main" program.
26 / 75
Control of Flow
MATLAB has four basic decives a programmer can use to control de ow of commands:
for loops if-else-end constructions while loops switch-case constructions
28 / 75
General structure:
for k=array ... end
Simple example
x=zeros(1,5) row of zeros to store for n=1:5 x(n)=n^2; end x= 1 4 9 16 25
Ferreira, C. and A. Netsunajev () MATLAB Tutorial 2011 February 10, 2011 30 / 75
end
2 3 4 4 6 8 6 9 12 8 12 16
February 10, 2011 31 / 75
MATLAB comparative advantage: vectorization and working with matrices. Nested loops are much slower than working with vectors the previous nested loop can be simplied: i=1:4; row vector 1 2 3 4 x=i * i ; vector multiplication. Careful with dimensions Also: always predene the matrix where you want to store
32 / 75
General structure:
d = d0 Initialize variable d while expression with d ... d = ... update d end Useful for iterations on recursive probems...
34 / 75
35 / 75
36 / 75
if-else-end constructions
Do some operations if some conditions hold.
General structure:
One alternative if expression ... end More than one alternative if expression 1 ... elseif expression 2 ... else ... end
Ferreira, C. and A. Netsunajev () MATLAB Tutorial 2011 February 10, 2011 38 / 75
Operator
Description Relational >, < greater / lower than >=, <= greater / less or equal == equal ~= not equal Logical & and | or ~ not
39 / 75
40 / 75
Theswitch-case construction
Switch compares the input expression to each case value. Once the match is found it executes the associated commands. For most practical cases, it achieves similar results to if-elseif-else constructions
General structure:
switch expression scalar or string case value1 executes if expression = value1 commands... case value2 commands... ... otherwise commands end
42 / 75
Try to program inside out: start with the inner section of your code, check it produces the desired results, and proceed towards the outer loops. In this way, you keep track of each step and possible errors. Ask MATLAB to print intermediate results / variable values. This is a good way to know exactly what is going on inside your code. Check the Workspace window: sometimes, either the dimensions of your matrices are not the ones you though... or matrices are just empty!!!
43 / 75
You can solve some tricky problems using some logical addressing. Two useful functions / operations:
find(.) nds indices of non-zero elements in an array (expression) acts as an indicator function: it takes value = 1 if expression holds
45 / 75
Find the indices where A>=4: ind1 = find(A >= 4) ind1 = 2 3 5 6 9 Operate over values of x that satisfy certain condition: z = (x.^2) . (x > 0.2) z = (0, 0.9421, 0.9162)
46 / 75
Basic commands
Be careful with function sqrt() using matrices. Consider example: 2 2 A= ; 2 2 B = sqrt(A) 1.4142 1.4142 B= ; 1.4142 1.4142 4 4 B B = 4 4 C = chol (A); 2 2 C C = 2 2
48 / 75
Programming
A variable is a tag that you assign to a value while that value remains in memory. You refer to the value using the the tag. You do not need to type or declare variables. MATLAB variable names must begin with a letter. MATLAB is case sensitive, so A and a are two dierent variables! Do not name a variable using a reserved names, such as i, j, mode, char , size and path.
49 / 75
Programming. Structures
Structures are multidimensional MATLAB arrays. This is very much like a database entity. Structures are useful to group variables. Let structure consist of 3 variables: Student.name, Student.score, Student.grade. The whole structure could be an input for user-dene function. It is convenient to use the structures when you have a lots of variables and you use your own functions. You wont need to pass all 3 variables to the function, but just the whole structure See provided example.
51 / 75
53 / 75
Programming. Debugging
Do you think your program is not producing the results that you expected? Then you can debug your program and see whats wrong. The standard debug tool are the breakpoints. Set breakpoints to pause execution of your program so you can examine values of variables where you think the problem can be. After setting breakpoints, run the le
56 / 75
Programming. Debugging
Then the Debug menu allows to: Run Commence execution of le and run until completion or until a breakpoint is met. Go Until Cursor Continue execution of le until the line where the cursor is positioned. Also available on the context menu. Step Execute the current line of the le. Step In Execute the current line of the le and, if the line is a call to another function, step into that function. Continue Resume execution of le until completion or until another breakpoint is encountered. Step Out After stepping in, run the rest of the called function or subfunction, leave the called function, and pause. Exit Debug Mode Exits debug mode.
Ferreira, C. and A. Netsunajev () MATLAB Tutorial 2011 February 10, 2011 57 / 75
2D Plots
There are many tools and ways for creating and editing your plots, both from the command line and by using the menus of Matlab (interface in the Figure window). It is possible to export your graph to nearly all conventional formats (.pcx, .bmp, .jpg, .pdf) via Save As option. See provided example on plots and subplots.
59 / 75
3D Plots
The primary method to create the 3D plot is the surf command which is used in combination with the meshgrid command. Meshgrid creates a matrix of (x , y) points over which the surface is to be plotted. See provided example on 3D plots.
61 / 75
MATLAB help
Matlab has the very user-friendly and extensive built-in and on-line help system. To access built-in help Type help in the Command Window Press F1 Go to Help menu Online users guide is available at http://www.mathworks.com/help/techdoc/matlab_product_ page.html Google the function you need end exploiting the web resourses available
62 / 75
B 1 B 1
T
1t|T ut ut
t=1
+
m=2
Tm 2
log det(m ) + 1 tr 2
B 1 1 B 1 m
mt|T ut ut
t=1
with respect to matrices m and B, taking other parameter as given, 0 0 0 possibly subject to B = and all elements of diag (m ) are 0.01.
Ferreira, C. and A. Netsunajev () MATLAB Tutorial 2011 February 10, 2011 67 / 75
68 / 75
Dening matrices
Return
Input x = [1 2 3]
69 / 75
Accessing matrices
Return
Comments create matrix element in 2nd row, 3rd col 3rd col 2nd row block
70 / 75
Special matrices
Return
Output 0 0 0 0 x= 0 0 0 0 1 1 1 x= 1 1 1 1 0 0 A= 0 1 0 0 0 1
Comments 2x4 matrix of zeros 2x3 matrix of ones 3x3 identity matrix
71 / 75
72 / 75
floor(x): rounds x towards minus innity ceil(x): rounds x towards plus innity round(x): rounds x towards nearest integer Let x = [0.2234 , -1.4434 , 5.3789]. Then: floor(x) = [0 , -2 , 5]. ceil(x) = [1 , -1 , 6]. round(x) = [0 , -1 , 5].
73 / 75
Two built-in functions to generate pseudo-random numbers: 1 rand(.); uniformly [0,1] distirbuted pseudo rn.
1 2 2 3
a = rand; generates a scalar-random number A = rand(n,m) generates an nxm matrix of random numbers
randn(.); (standard) normally distributed pseudo-rn rand(state,0) or randn(state,0) useful to repeat a computation using the same sequence of pseudo- random numbers.
74 / 75
Return
Two alternative ways of generating normally distributed (pseudo) rn: 1 probability integral transform property: if U is distributed uniformly on (0,1), then 1 (U) will have the standard normal distribution. 2 (approximation) Central Limit Theorem! Generate 12 U [0, 1] , add them up, and substract 6. (11th order polynomial approx. to the normal distribution)
75 / 75