Difference between revisions of "Discussion"

From ECLR
Jump to: navigation, search
Line 55: Line 55:
 
<li><p><source enclose=none>b = A(2,:)</source>, this saves the entire 2nd row in variable b</p></li>
 
<li><p><source enclose=none>b = A(2,:)</source>, this saves the entire 2nd row in variable b</p></li>
 
<li><p><source enclose=none>B = A(4:end,:)</source>, this saves rows 4, 5, 6, up to the last (end) row of A in variable B (assuming A has at least 4 rows).</p></li>
 
<li><p><source enclose=none>B = A(4:end,:)</source>, this saves rows 4, 5, 6, up to the last (end) row of A in variable B (assuming A has at least 4 rows).</p></li>
<li><p><source enclose="none">B = A([2 4 5],:)</source>, this saves rows 2, 4 and 5 of A in variable B (assuming A has at least 5 rows). The same is achieved by <source enclose="none">B = A(c,:)</source> if <source enclose="none">c</source> is defined as <source enclose="none">[2 4 5]</source>. This is extremely useful when it comes to selecting data (see a later exercise).</p></li>
+
<li><p><source enclose="none">B = A([2 4 5],:)</source>, this saves rows 2, 4 and 5 of A in variable B (assuming A has at least 5 rows). The same is achieved by <source enclose="none">B = A(c,:)</source> if <source enclose="none">c</source> is defined as <source enclose="none">c = [2 4 5]</source>. This is extremely useful when it comes to selecting data (see a later exercise).</p></li>
 
<li><p><source enclose=none>b = A(:,5)</source>, this saves the entire 5th column in variable b</p></li>
 
<li><p><source enclose=none>b = A(:,5)</source>, this saves the entire 5th column in variable b</p></li>
 
<li><p><source enclose=none>B = A(:,3:end-1)</source>, this saves the following columns of A in a new matrix B: columns 3, 4, 5, etc. up to and including the last but one column.</p></li></ul>
 
<li><p><source enclose=none>B = A(:,3:end-1)</source>, this saves the following columns of A in a new matrix B: columns 3, 4, 5, etc. up to and including the last but one column.</p></li></ul>

Revision as of 13:26, 29 September 2012

Programming in MATLAB

We now consider how to create, edit and execute m–files. But initially we will have a brief look at the MATLAB screen.

0.5cm 0.5cm

This is how MATLAB looks on my machine although it may be arranged slightly differently on yours. However the 4 main elements A to D will always be there and I will briefly explain them

  • Window A: This is the current directory.
  • Window B: This is the editor window in which you can change MATLAB scripts and functions.
  • Window C: This is called the command window. You can do basic clalculations in here (Type 3+2 and press ENTER) and any outputs of your MATLAB code will be printed in here.
  • Window D: In this window you will be able to look at individual variables that have been defined in your code.

Creating and executing script m-files

You can use MATLAB to perform individual operations by just typing them into the command window (Window C). However, the strength of MATLAB lies in collecting a whole bunch of commands and then executing them in one go. Such a bunch of commands is usually written into an m–file.

An m–file can be created using the MATLAB Editor. To do this, click on File at the top of the MATLAB window and then select New followed by m–file. You will then be in the editor. Enter the commands:

C = [5 4; 3 2]; % Create 2x2 matrix
dc = det(C);    % Calculate determinant
disp(dc);       % Display value of dc

Everything following a % are comments and are ignired by MATLAB. It is good practice to use a lot of comments.

Now save the program into a file called test1.m. For now you created a collection of commands (three to be precise). What you now want is to tell MATLAB that you want it to execute these commands (of course you will typically have many more than three commands).

To execute this program type test1 on the command line in the MATLAB Command window and then hit enter[1]. You can then seen that test1.m causes det(C) to be printed into the command window. At this stage you will also see two objects in the workspace (Window D), namely C and dc. You can use them in new calculations in the command window, say type
2*dc and the ENTER.


In the above collection of commands you can see that every command was followed by a semicolon(;). If you do so the result of the operation will be saved in MATLAB’s workspace but not printed onto the screen. This should be your default mode. If you want to see something on the screen you can either leave away the semicolon, or better use the command disp(VARIABLENAME); as was done in the third line of the code.

If you want to edit an already existing m file you merely need to open it. It will appear in the editor window and away you go.

Some basic MATLAB commands

To work with MATLAB you need to know a few basic things. Data are saved and handled in matrices (vectors and scalars are just special cases of matrices). Here are a few useful commands to create matrices/vecors[2].

  • C = zeros(4,3), this creates a new matrix C with 4 rows and 3 columns and all values 0.

  • D = ones(7,1), this creates a new matrix (vector) D with 7 rows and 1 column and all values 1.

  • A = [1 2; 3 4]; this enters the following matrix

    [math]A=\left[ \begin{array}{cc} 1 & 2 \\ 3 & 4% \end{array}% \,\right][/math]

    Elements in one row are seperated by a space (although you could also use a , and a ; indicates that the next element is the first element in a new row.

  • b = A(2,3), this saves the element from the 2nd row and 3rd columns of A in the new variable b.

  • c = 1:5, creates a [math](1\times5)[/math] row vector with the numbers 1 to 5

  • c = 2:3:14, creates a row vectors with numbers starting at 2 up to 14, but in steps of 3

  • b = A(2,:), this saves the entire 2nd row in variable b

  • B = A(4:end,:), this saves rows 4, 5, 6, up to the last (end) row of A in variable B (assuming A has at least 4 rows).

  • B = A([2 4 5],:), this saves rows 2, 4 and 5 of A in variable B (assuming A has at least 5 rows). The same is achieved by B = A(c,:) if c is defined as c = [2 4 5]. This is extremely useful when it comes to selecting data (see a later exercise).

  • b = A(:,5), this saves the entire 5th column in variable b

  • B = A(:,3:end-1), this saves the following columns of A in a new matrix B: columns 3, 4, 5, etc. up to and including the last but one column.

It will often be useful to figure out how big a matrix is. Say you have a matrix D, then the following commands can be very useful:

  • [r,c] = size(D), this saves the number of rows of D in the new variable r and the number of columns in the new variable c.
  • r = size(D,1), this saves the number of rows of D in the new variable r.
  • c = size(D,2), this saves the number of columns of D in the new variable c.
  • l = length(D), this saves the larger of the number of rows or columns in the new variable l.

Let’s say we have a matrix A. In order to access particular elements of that matrix you need to follow the following conventions:

  • A(6,2) = 4, this puts the value 4 on the (6,2) element of A
  • A(:,1) = ones(size(A,1),1), this replaces the entire first column of matrix A with a vector of 1s. Note that to ensure that the vector of ones that is to be put into the first column of A is created to have exactly the same number of rows as A.

Mathematical operations are pretty straightforward in MATLAB. You just have to use the conventional mathematical commands:

  • C+D, if C and D are matrices their dimensions will have to be identical. If one of them (say C) is a scalar that value will be added to each element of the other (say D).
  • C*D, if C and D are matrices their dimensions will have to be such that a matrix multiplication is allowed
  • C.*D, multiplies each element in C with the corresponding element in D. The matrices have to have identical dimensions for this operation to work. The . in front of an any operator indicates an element-by-element operation.
  • C./D, divides each element in C with the corresponding element in D. The matrices have to have identical dimensions for this operation to work. The command C/D is not so straightforward as you may recall from matrix algebra that there was not a straightforward matrix division. But in MATLAB C/D is by and large the same as [math]C(D^{-1})[/math].
  • a = b^c, calculates [math]b^{c}[/math] but works only for scalars.
  • a = sqrt(b), calculates the square root of b.
  • E = C’, saves the transpose of C in the new variable E.
  • E = C’*C, calculates C’C and saves it in the new variable E.
  • A = [B C], creates a matrix A, which consists of the two matrices B and C attached to each other sideways. B and C need to have the same number of rows. (horizontal concatenation)
  • A = [B; C], creates a matrix A, which stacks the two matrices B and C on top of each other. B and C need to have the same number of columns. (vertical concatenation)

Some basic MATLAB functions for matrices

In a later module you can read about functions in MATLAB. But in short they are little pieces of code that perform some pre-specified operations. In the context of matrices you may have some painful memories of having to calculate the inverse of a matrix by hand. Wouldn’t it be nice if MATLAB could do this with one little command. Well you are in luck, MATLAB can. The inverse of the matrix A can be calculated by using inv(A).

Well, this is only a half truth. MATLAB will still have to do all the painstaking operations required for the calculation of a matrix inverse, but it will do this all by itself and in the background as one clever programmer wrote a little piece of software that you call up, by typing inv(A). Such a piece of software is called MATLAB. In a later module you can learn how to write such functions yourself. In fact it is very likely that you will wan to do this to make your life easier.

Here is a list of useful matrix functions in MATLAB:

  • [nr,nc] = size(A), the size command returns information on how many rows (nr) and how many columns (nc) the matrix A has (You choose the names for the output variables, here nr and nc, yourself). You can achieve the same by the following two seperate commands nr = size(A,1)nc = size(A,2)
  • r = rank(A), this delivers the rank of a matrix
  • d = det(A), The determinant of A
  • C = inv(A),The inverse of A
  • t = trace(A), The trace of A
  • e = diag(A), saves the diagonal of matrix A in a column vector e.
  • a = sum(A), saves the sum of each column in a row vector a. The vector a will have as many elements as A has columns.
  • a = mean(A), saves the aritmetic average of each column in a row vector a. The vector a will have as many elements as A has columns.
  • b = std(A), saves the sample standard deviation of each column in a row vector b. The vector a will have as many elements as A has columns.
  • c = skewness(A), saves the sample skewness of each column in a row vector c. The vector a will have as many elements as A has columns.
  • d = kurtosis(A), saves the sample kurtosis of each column in a row vector d. The vector a will have as many elements as A has columns.
  • B = sqrt(A), saves a matrix with the square root of every element of A in the matrix B. B will have the same dimension as A.
  • [v,e] = eig(X), calculates the eigenvalues (e) and eigenvectors (v) of matrix [math]X[/math].
  • repmat(A,m,n), Replicates matrix A, m times on top of each other, n times next to each other
  • reshape(X,r,c), reshapes a [math]\left( n\times p\right) [/math] matrix [math]X[/math] into a [math]\left( r\times c\right) [/math] matrix. Number of elements have to remain the same.
  • flipud(X), flips a matrix [math]X[/math] upside down
  • fliplr(X), flips a matrix [math]X[/math] sideways

Error messages and coding practice

Error messages is MATLAB’s way of communicating with you (in educational speak giving you formative feedback on your effort to writing a program). They usually contain two pieces of information.

  1. Where in the code the mistake occurred
  2. What went wrong, which gives you a hint on what to do to fix it. This part is at times cryptic at best.

Sometimes you get a whole list of error messages. However, only tackle the error that occurs first in the code. All other error messages may disappear after having fixed the first problem. You should be careful and not think that just because MATLAB did not give you an error message everything is alright. All the absence of MATLAB error messages means is that MATLAB could indeed undertake all instructions it obtained from you. It DOES NOT imply that all the instructions which you passed on to MATLAB are indeed the instructions you had intended.

This implies the following rules for good program writing:

  1. Use extensive comments in your code in order to write down what you intended to do at a particular place in the code. Everything that follows a % in the code is ignored by MATLAB, and hence is a comment intended for yourself or someone else
  2. Write the code bit by bit and check its workings as you write it in small steps
  3. Where possible check whether the results you obtain are sensible

Footnotes

  1. For this to work, the current folder (see the field just underneath the menus needs to be set to the folder in which you saved this m file
  2. Here we use the following naming convention. Matrices will be labeled with capitalised letters and vectors and scalars will be labeled with small letters.