You are on page 1of 4

This crash-course is designed for advanced students who have strong experience with various programming languages.

As such, we will not spend time on fundamentals of programming, and jump straight to MATLABs unique features. 1. Creating Vectors: The fist thing to consider when using MATLAB is the native support of vectors and matrices. The concatenation operator are the square brackets: [] . try these: a. a=1 b. b=2 c. c=[a b] d. rowVec=[5 3 9 a 8 b 5.5] e. colVec=[9;8;7;6] Any scalar variable (e.g., a) is just a vector of size 1! We also introduce the colon operator :. In the context of creating vectors, it has two modes of use: f. 1:5 g. 3:0.4:9 In the first, an interval is not specified, and so the default is used 1. In the two-colon operator, an interval is explicitly specified. Note that the last number might not be part of the resulting vector try h. 3:7.99 i. 7.99:-1:3 The apostrophe operator transposes a vector it switches between rows and columns. Try: j. colVecT=rowVec 2. Indexing Vectors In order to access the elements of a vector, we use the parentheses (). In MATLAB, the first index is 1 (and not 0 like C/C++/Java/Python)! Try these: a. rowVec(1) b. colVec(2) c. rowVec(end) d. colVec(end-1) e. colVec([1 3]) f. rowVec(2:4) g. rowVec([1 1 1]) We learned two new things here: (1) the reserved word end, when used in an indexing context, is interpreted to mean the last element; (2) vectors of indices can be used to index multiple entries of vectors. These can be constructed by either explicit concatenation, or by the colon operator. Note the repeated use of the same index in the last example. Can you find a way to reverse a vector? Hint: use the two-colon operator, and the reserved word end. 3. Creating Matrices We can concatenate several vectors together and form a matrix, as long as they are of the same dimension. Try these: a. colVec2=[2;3;4;5] b. myFirstMatrix=[colVec colVec2] c. c2=[5 9],c3=[4 7] d. VertCat=[c;c2;c3] Note the use of the comma operator to separate two statements. Compare (c,d) above with: e. c2=[5 9];c3=[4 7]; VertCat=[c;c2;c3] Terminating a statement with the semicolon suppresses output to the command window.

Any k-element vector is simply a k-by-1 (or 1-by-k) matrix! Finally, the transpose operator will switch rows and columns. f. horMat=VertCat 4. Indexing Matrices a. in order to pull the number at row i and column j of matrix M (denoted Mij), we use the coma, using the row index FIRST. This is called subscript indexing. For example, the element at the third row, second column of the matrix VertCat is called by: VertCat(3,2) b. We can also use a single number to index a matrix. This is called linear indexing. By convention, the order of the elements is: down the rows first, then across the columns. REMEMBER: ROWS FIRST! Look at myFirstMatrix(2) and myFirstMatrix(7) do you understand why you got these answers? c. If we want to access a number of indices, we specify them as above. For example, the first three entries of the second column of myFirstMatrix are indexed as myFirstMatrix(1:3,2) d. The transpose operator will swap rows and columns. So if mt= myFirstMatrix; what is mt(2,1:3)? What is mt(2,1:3) ? 5. Scripts The MATLAB editor allows us to write code in a text file, and execute it all at once. The suffix of MATLAB scripts (and functions, see below) is .m, and the filename MUST NEVER begin with a number. Why? Because when we execute a script, it is called by its name. Try it: copy some of the lines from your command history to a text file (make sure to include only lines that didnt have syntax errors! Two or three will suffice), and save it as test1.m. Type test1 in the command window (first, make sure your working directory, specified in the top-middle, matches the location of the file). Open the file in the MATLAB editor, and hit the run button. Now re-save the file under a different name :1test.m, and try to run it. 6. for- loops As opposed to Java and C/C++, in MATLAB the for loop always iterates over columns of a matrix. Try these: a. for ind=1:5 2*ind end b. aggregator=0; for ind=1:7 aggregator = aggregator + rowVec(ind); end aggregator c. for v= horMat v end Note the use of the reserved word end in a different context (flow control). Example (b) calculates the sum of the elements of rowVec. Note how a semicolon was added to the end of the command inside the loop to suppress output to the command window. As a general rule, your codes output to the command window should be regulated dont make a mess of it!

Write a loop that would sum every row in a matrix, and return the column vector of these row sums. Its OK to hard-code the size of the matrix, and have it run only on one particular example dont build a general-purpose tool! Write a triple loop that calculates the multiplication of these two matrices: A=[1 2 3;4 5 6],B=[9 8 7 6;8 7 6 5;7 6 5 4] A reminder: if C=AB, then Cij=kAikBkj. Again feel free to hard-code all loop limits.

7. Built-in functions MATLAB has a vast set of built-in functions. Inputs to functions are handed over using the parentheses. Try all of these: a. sum(rowVec) b. sum(horMat,2) c. size(VertCat) d. size(VertCat,1) e. repmat(rowVec,[1 3]) f. repmat(rowVec,[2 3]) g. circshift(rowVec,[0 -1]) h. zeros(3,5) i. ones(3,5) j. rand(3,5) k. randn(3,5) l. diag([5 3 1]) m. diag(rand(4)) The input-output structure of built-in functions (and much more) is found by using help (e.g., type help sum). Note the functions often return vectors or matrices. Note also that functions can accept variable number of inputs (compare (a) and (b) above) and outputs (see (k) below). Try to replace the inner loop in your matrix multiplication code to use the function sum. In MATLAB, functions may have multiple outputs. Try: n. [minVal, minInd]=min(rowVec) Note that in this context, the square brackets here are not used for creating a matrix! 8. Writing your own function The syntax for creating a MATLAB function is: function [out1,out2,,outn]= funName(in1, in2,,ink) This must be the first line of code in the file funName.m. Take your code for multiplying matrices, and create a general function for matrix multiplication. Parameterize the span of the loop according to the dimensions of the input matrices using size. 9. Vector and Matrix operations We can perform element-wise operations on matrices of identical sizes: A=rand(5),B=100*eye(5), C=A+B,D=A.*B The plus and minus operators are always element-wise. The dot-star .* operator multiplies the matrices element-wise. What happens if you type B./A? We can also perform matrix algebra: a. A*B b. B*rand(5,1) A scalar input would be applied to all the elements of the matrix. Try eye(5)+2

An example: A=rand(1,10) are 10 data points. We can find the Residual-Mean-Square (RMS) distance between these points and some fixed point x=0.7 by: C=A-x;sqrt(sum(C.^2)) Suppose our data is 2-dimensional: B=rand(2,10); This: C=B-x; sqrt(sum(C.^2)) would still work, but would yield nonsensical results, because we subtract 0.7 from both dimensions! Suppose x=[0.7;0.2]; now C=B-x wouldnt wok, because the dimensions dont match. There are 4 ways of dealing with it: a. Building C with a for-loop: inefficient (if youre not sure how, try it!) b. C=B-x(:,ones(1,size(B,2))) c. C=B-repmat(x,[1 size(B,2)]) d. C=bsxfun(@minus,B,x) I dont know which of the last three is the most efficient. Suppose we have a 3D vector v=[4;3;2]; We can scale the dimensions: vscale=diag([1 10 1])*v We can take the inner product v*v, and we can take the scaled inner product: v*diag([5 3 1])*v What if we had many 3D vectors in a matrix V=randn(3,10) ? The vector of inner products can be calculated by sum(V.*V,1), and the scaled inner product is: Sum(V.*(diag([5 3 1])*V),1)

You might also like