You are on page 1of 25

# Introduction to MATLAB

## Alex Chen after material from Todd Wittman

UCLA Applied Math REU

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

Why MATLAB?

MATLAB (Matrix Laboratory) is a programming language especially useful for linear algebra computations. Various operations involving matrices, grids, and arrays (i.e. images) can be written concisely and neatly using MATLAB.

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

A Fancy Calculator
If they understand nothing else, you can show your parents, signicant others, and North Campus friends that you have a fancy calculator: 2+3 ans = 5 To suppress the output, use a semicolon: 2 + 3; The up arrow repeats the last input (you can also type in part of a previous command and press the up arrow until you reach the command you want). Other possible functions: exp (2), sin(pi ), asin(2) Sometimes, you will have the values Inf and NaN
Alex Chen after material from Todd Wittman Introduction to MATLAB

More Arithmetic

mod (27, 5) = 2 round (27.6) = 28 oor (27.6) = 27 ceil (27.6) = 28 abs (3) = 3

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

Variables

Variables can be used without declaration: x = 2 The type can also be changed easily: x = hello A list of variables can be obtained with the command: who Even more useful is to open up the workspace window: Desktop Workspace To delete one variable: clear x To delete all variables: clear all Be careful with this one! To save your workspace: save todayswork To save a selection of variables save todayswork x y z

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

Vectors

Vectors are enclosed by square brackets: v = [2 3 4 5 6] v (2) gives 3 as output. v ([2, 4]) gives [3 5] as output. The colon operator takes a range: v = 2 : 6 One can also take the even numbers: evens = 2 : 2 : 100 (default step = 1) Or in descending order: 100 : 2 : 2 A column vector is obtained by using transpose: v

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

Matrices
A 2D matrix is formed by placing a semicolon after each row: A = [2 3 4; 5 6 7] gives 234 567 We can look up values by row, column: A(2, 3) = 7 Use a colon for the entire row or column: A(:, 3) Look up sections with a colon: A(1 : 2, 2 : 3) or by vectors choosing the rows and columns: A(:, [1 3]) Repeat blocks to form a larger matrix: repmat (A, [2 3])
Alex Chen after material from Todd Wittman Introduction to MATLAB

## Other Useful Matrices

Uniform random number generation from [0, 1] of 10 rows by 20 columns: rand (10, 20) 3 3 identity matrix: eye (3) 4 5 zero matrix: zeros (4, 5) 3 2 matrix of ones: ones (3, 2) A matrix with 1, 2, 3, 4 down the diagonal, zeros everywhere else: diag (1 : 4) A matrix with 1, 2, 3, 4 down the diagonal one entry below the main diagonal: diag (1 : 4, 1)

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

Matrix Operations 1
Matrix multiplication: A B , A 3 Component-wise operations: A. B , A. 3 Be very careful here to distinguish between matrix multiplication and component-wise operations. Many errors by newcomers to MATLAB are caused by using A B when you actually mean A. B Transpose: A Look up matrix size: size (A) Eigenvalues: [v , d ] = eig (A) where v = a vector of eigenvectors with d a diagonal matrix of the corresponding eigenvalues. Note: Many built-in functions give multiple outputs. When such functions are used, brackets are used as in eig. eig(A) gives something slightly dierent: the eigenvalues of A.
Alex Chen after material from Todd Wittman Introduction to MATLAB

Matrix Operations 2

Vectorize a matrix A = [1 2 3; 4 5 6]: A(:) gives [1 4 2 5 3 6] Another way: B = reshape (A, [6, 1]) Putting it back: reshape (B , [2, 3]) Reversing the order of the rows of A: ipud (A) Reversing the order of the columns of A: iplr (A) Another way: A(end : 1 : 1, :), A(:, end : 1 : 1)

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

Norms

L2 norm of vector: norm(a) Lp norm of vector: norm(a,p) L2 norm of matrix: norm(A(:)) Careful here! Matrix norm: norm(A)

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

Solving Ax = b

Inverse: inv (A) But: solving the system Ax = b is more eciently done by using the backslash operator: x = A\b If A is singular, attempting to solve Ax = b by the pseudoinverse pinv (A) gives the least squares solution to Ax = b : x = pinv (A) b The function linsolve can also be used: linsolve (A, b )

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

Logic Functions

A = [1 2 3; 1 5 3]; A == 1 gives a matrix that compares each element to 1. Also, A = 1 & and | are the and and or functions, respectively: [1 2] & [0 2] isnan, isinf , isnite check whether each element in a matrix is NaN, Inf, or nite.

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

## Navigating the Lost and Found

A = [1 2 5; 2 3 6]; [row col ] = nd (A < 3 & A > 1); nds the indices where A is between 1 and 3. Sort in ascending order: sort([5 1 6 2 3]); Descending: sort([5 1 6 2 3], descend);

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

Statistics 101

Vector and matrix min: mina = min(a); minA = min(min(A)); Also max Sum of vector: sum(a) Sum of matrix: sum(sum(A)) Cumulative sum: cumsum(a) Mean of vector: mean(a) Mean of matrix: mean(mean(A)) or mean(A(:)) Also variance: var (a), var (A(:)) Covariance matrix: cov (A) Uniform double from [0,1]: rand Randomly permute the integers from 1 to n: randperm(n)

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

Statistics 102

x = 10 : 0.1 : 10; plot (x , normpdf (x )) plot (x , normcdf (x )) x = 0 : 10; plot (x , poisspdf (x , 1)) or plot (x , pdf ( Poisson , x , 1)) x = random( Normal , 0, 1, 2, 4) gives a 2 4 matrix of entries sampled from N (0, 1) (and, of course, other distributions are possible, see MATLAB help).

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

Symbolic Variables (or What Your Calculus Teacher Didnt Want You to Know)
Symbolic variables allow the calculation of derivatives and integrals. syms x ; di (3 x 2 + 6 x 4) ans = 6x +6 int (exp (2 x )) ans = 1/2 exp (2 x )

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

save and clear have already been mentioned. load todayswork loads .mat les that were previously saved. load can also load numeric text les (in this case, you need to use the full extension load textle.txt).

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

Read an image: a = imread ( imagele .png ); Convert format of variable: a = double (a), a = uint 8(a) This step is important since many computations can only be done in double. Display an image: imagesc (a) Convert to grayscale: colormap gray ; Convert to false color (default): colormap jet ; Write an image: imwrite (a, newimagele .png , png ) The image may need to be scaled to take values in [0,1] when using this function. These may also be saved directly from the displayed gure, but they will look slightly dierent.

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

Basic Graphics
x = 0 : 0.01 : 1; y = x. 2 plot (x , y ) hold on allows multiple lines to be plotted: hold on; plot (x , x . 3, r ); You can also change the color and style of the line. Type help plot for more details. The axis range can be set: axis (0, 1, 0, 2) title ( Parabola ) Other functions: xlabel, ylabel, legend An excellent resource on creating graphs in MATLAB: http://blogs.mathworks.com/loren/2007/12/11/ making-pretty-graphs/
Alex Chen after material from Todd Wittman Introduction to MATLAB

Surface Plots

x = 1 : 0.05 : 1; y = 1 : 0.05 : 1; Making a surface plot requires the arguments to be 2D variables: [x 1, y 1] = meshgrid (x , y ); surf (x 1, y 1, x 1. 2 + y 1. 2) You can rotate these plots, look at specic data points, and zoom in and out (this can be done for images as well). Explore the various buttons in the toolbar.

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

## Functions and Scripts

.m les are collections of commands that can be executed at once as a program. Scripts are executed just as if the commands were written in the command window. Thus, the variables used in a script are stored. In a function, the variables are not stored, and the operation is similar to the built-in functions in MATLAB. The only dierence in syntax is that functions have the line function[a, b ] = myfunction(var 1, var 2) at the beginning. Also, more functions can be dened within one .m function le, but this cannot be done for scripts. Comments are prefaced by the % sign.

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

## Loops and Control Statements

while i > 0 ... end if x > 0 ... elseif x < 0 ... else for i = 1 : 10 ... end ... end

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

Loop Speed

Note: Loops in MATLAB often signicantly slow down a program. Matrix operations have been optimized by MATLAB and should be used whenever possible. More about avoiding loops will be given in the next MATLAB class.

## Alex Chen after material from Todd Wittman

Introduction to MATLAB

## Other Resources for Code

MATLAB has very good help documentation: help linsolve Or google matlab linsolve , as the documentation is a little dierent (with other examples). MATLAB tutorials on the MATLAB channel on youtube. MATLAB central le exchange. It is often easiest to access these functions (and others) by searching on google: Chan Vese segmentation matlab. The website of Pascal Getreuer (UCLA 10): http://www.math.ucla.edu/~getreuer Image processing online, a journal with many common and cutting-edge image processing algorithms (not MATLAB): http://ipol.im

## Alex Chen after material from Todd Wittman

Introduction to MATLAB