19 views

Uploaded by Rahul Sukhija

matlab intro

- Basic Mat Lab
- MATH 120-Linear Algebra With Differential Equations- Faqir M.bhatti & Muhammad Saqib
- 0912 ch01
- 2016-iscPracticalSpecimen
- Ch 3 Watermark
- Matrix.algebra
- Maple by Example
- Symmetric With 1 Pos Eigen
- coupled_oscillations.pdf
- LN4_diagonalization
- Feedback
- ml.pdf
- Aditya Nigam Ccbr2011P
- WS_HMatrices
- MATLAB Workshop
- m225
- 0606_s14_qp_12
- fgswfssfsfsfsf.docx
- MATLAB Workshop
- R subnetting

You are on page 1of 25

UCLA Applied Math REU

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.

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

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

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

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

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)

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)

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)

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 )

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.

Introduction to MATLAB

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);

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)

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).

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 )

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).

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.

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.

Introduction to MATLAB

.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.

Introduction to MATLAB

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

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.

Introduction to MATLAB

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

Introduction to MATLAB

- Basic Mat LabUploaded byJudap Floc
- MATH 120-Linear Algebra With Differential Equations- Faqir M.bhatti & Muhammad SaqibUploaded byShameen Elahi
- 0912 ch01Uploaded byvest62
- 2016-iscPracticalSpecimenUploaded bybest of all things ANSHU
- Ch 3 WatermarkUploaded byAasheesh Sahu
- Matrix.algebraUploaded byKeith W Barnwell
- Maple by ExampleUploaded bytresttia_tresttia
- Symmetric With 1 Pos EigenUploaded bySara Ahmadi
- coupled_oscillations.pdfUploaded byShweta Sridhar
- LN4_diagonalizationUploaded byNikhilesh Prabhakar
- FeedbackUploaded byJoshua Cruz
- ml.pdfUploaded byమత్సా చంద్ర శేఖర్
- Aditya Nigam Ccbr2011PUploaded bySanjeev Panwar
- WS_HMatricesUploaded byinsomniacsh
- MATLAB WorkshopUploaded byTewodros
- m225Uploaded byAakash Verma
- 0606_s14_qp_12Uploaded bysriniyfa
- fgswfssfsfsfsf.docxUploaded byragvshah
- MATLAB WorkshopUploaded byAjit Kumar
- R subnettingUploaded byManuj Satha
- 313 Final Review.nbUploaded byanon_818806301
- Summer Training in MatlabUploaded bymjcetpa
- Mathematics Paper With Answer Solution Paper 1Uploaded byJatin Gupta
- A Comprehensive Computer Program for Small Signal Stability Analysis of Power SystemsUploaded byphieuxuatkho
- Emotion Classification Using Facial ExpressionUploaded byEditor IJACSA
- Giles Stability of ODE SolversUploaded byTomek Dysarz
- B.tech 1st Sem Computer COT-101 Nov, Dec 2013Uploaded byDanny Adonis
- List_of_matrices.pdfUploaded bymars
- CSE123_Lecture04_2013.pdfUploaded byHasanMert
- MP01Uploaded byTresia Cercado

- Cluster_Analysis_usingR.pdfUploaded byRahul Sukhija
- Cs221 ReportUploaded byRahul Sukhija
- ExamplesUploaded byRahul Sukhija
- Multiple RegressionUploaded byHernán Covarrubias
- Twitter API Sentiment AnalysisUploaded byRahul Sukhija
- Moving AveragesUploaded byRahul Sukhija
- MATLAB TutorialUploaded byKrishna Kumar
- Sentence Level Sentiment AnalysisUploaded byRahul Sukhija
- Matlab Tutorial BeginnerUploaded byAriel Villca Paye
- Semantic Sentiment Analysis of TwitterUploaded byZaqi Syah
- _type_ in Proc SummaryUploaded byRahul Sukhija
- matlab basics.pdfUploaded byRahul Sukhija
- ReadmeUploaded byRahul Sukhija
- Using Arrays in SAS ProgrammingUploaded byipiranga_1
- Matlab TutorialUploaded byapi-25906715
- Gentle Lentil Case.pdfUploaded byRahul Sukhija
- My Knowledge GMATUploaded byRahul Sukhija
- Base SAS Certification SamplesUploaded byRahul Sukhija
- GIN's RC TechniqueUploaded bydinmilo
- Sentence Corrections PracticeUploaded byapi-3827626

- RHCE7-3Uploaded byHarshal Tapadiya
- US Federal Reserve: SR0519a1Uploaded byThe Fed
- Game Save Manager Supported GamesUploaded byLuke Anthony Mason
- Jargon Buster Guide to GDPRUploaded byMiltonThitswalo
- Git Branching.pdfUploaded byPrabal Kajla
- 78820173 Persona Management Methods 130502144237 Phpapp01Uploaded byHutch Rev Oliver
- Engineering Mechanics Statics - 3rd Ed - Andrew Pytel & Jaan Kiusalaas_ANEXO AUploaded byysmael82
- CNBI FCC Certificate of Compliance.pdfUploaded byFederal Communications Commission (FCC)
- 03-Overview of Cryptographic Techniques (1)Uploaded byShahul Ahamed
- Assignment 01Uploaded bySultan Tariq
- Nadhem Alfardan Get VPNUploaded byBeenish Shaikh
- Anonymous Query Processing in Road NetworksUploaded byVinaya Kumar S
- Dhs Occupy 3Uploaded byglennallyn
- Forrester Best Defense NGFW Zero Trust Security Executive SummaryUploaded byAhsan Zia
- identity theft webquestUploaded byapi-256439485
- database privilege escalationUploaded byapi-234168635
- Assignment 1 Tac04242015Uploaded byTerri A Cooks
- Digital Image Based Data Hiding by Using SteganographyUploaded byInternational Journal of Innovative Science and Research Technology
- Oregon Open Government Guide Reporters Committee for Freedom of the Press.pdfUploaded byMark Reinhardt
- Awareness of Social Engineering Among IIUM StudentsUploaded byWorld of Computer Science and Information Technology Journal
- Extrabold It s More Than a Book PDFUploaded byTonya
- CiscoUploaded byFarooq
- Secure Atm by Image ProcessingUploaded bySara Vanan
- Transposition CipherUploaded byEwa Tenerowicz
- WA State AG Complaint - 144Uploaded byCopyright Anti-Bullying Act (CABA Law)
- Lecture 02 Introduction CryptographyUploaded byNguyễn Huu Sang Nguyễn
- CAST HowToGuideUploaded byAmigoss Enmovimiento
- 10+ dgUploaded byBLN
- Concept of AlgorithmUploaded byKiran Srivastava
- 1906 Service Manual (Cct's Incomplete + Iss Nos Different)Uploaded bysdspig