1 / 28

Introduction to Matlab 7

Introduction to Matlab 7. Part II. Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften ETH Hönggerberg / HCI F128 – Zürich E-Mail: daniel.baur@chem.ethz.ch http://www.morbidelli-group.ethz.ch/education/snm/Matlab . Review of Vectors. Vector handling

binh
Download Presentation

Introduction to Matlab 7

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Matlab 7 Part II Daniel BaurETH Zurich, Institut für Chemie- und BioingenieurwissenschaftenETH Hönggerberg / HCI F128 – ZürichE-Mail: daniel.baur@chem.ethz.chhttp://www.morbidelli-group.ethz.ch/education/snm/Matlab Daniel Baur / Introduction to Matlab Part II

  2. Review of Vectors • Vector handling • Row vector: a = [1 2 3]; a = [1, 2, 3]; • Column vector: b = [1; 2; 3]; • Vector with defined spacing: c = 0:5:100; (or 0:100) • Vector with even spacing: d = linspace(0, 100, 21);e = logspace(0, 3, 25); • Transpose: f = e'; Daniel Baur / Introduction to Matlab Part II

  3. Review of Matrices • Creating matrices • Direct: A = [1 2 3; 4 5 6; 7 8 9]; • Matrix of zeros: B = zeros(3,2); • Matrix of ones: C = ones(3,2); • Random matrix: R = rand(3,2); • Normally distributed: RD = randn(2,3); • Matrix characteristics • Size [nRows, nColumns] = size(A); nColumns = size(A,2); • Largest dimension maxDim = length(A); • Number of elements nElements = numel(A); • Creating vectors • Single argument calls create a square matrix, therefore use commands like v = ones(3,1); to create vectors Daniel Baur / Introduction to Matlab Part II

  4. Review of Accessing Elements • Vectors (a = (1:5).^2;) • Single element: a(3); • Multiple elemets: a([1, 3]); • Range of elements: a(2:4); • Last element: a(end); • All elements: a(:); • Matrices (A = a'*a;) • Single element: A(1,3); • Submatrix: A(2:3,2:3); • Entire row / column A(2,:); A(:,3); • Multiple rows / columns A([2, 3],[1, 3, 5]); • Last element of row / column A(2,end); A(end,3); • All elements as column vector A(:); a(:) always returns a column vector. Daniel Baur / Introduction to Matlab Part II

  5. Review of Matrix Operations Create a Matrix • A = rand(3); Operations with constants • B = 2*A • C = 2+A Matrix addition; Transpose • D = A+C • D = D' Deleting rows / columns • C(3,:) = []; • D(:,2) = []; Matrix multiplication • C*D • D*C Not commutative! • A^2 Element-by-element operations • A.^2 • E = 2.^A; Ei,j = 2^Ai,j • sqrt(A) Functions using matrices • sqrtm(A) • sqrtm(A)^2 • inv(A) Daniel Baur / Introduction to Matlab Part II

  6. Review of Matrix Operations (Continued) • Matrix properties • sum(A,dim); • det(A); • inv(A); • eig(A); • More creation options and reshaping • B = [ones(4); diag(1:4); eye(4)]; • B = reshape(B, 24, 6); • C = repmat(B, 1, 3); • Solution of linear algebraic systems • A = rand(3); • b = rand(3,1); • x = A\b; • Do not usex = inv(A)*b! Daniel Baur / Introduction to Matlab Part II

  7. M-Files • What is an m-file? • An m-file is a collection of commands. It is equivalent to programs, functions, subroutines, modules, etc. in other programming languages. It can even contain entire class definitions. • What can I use it for? • Creating a permanent record of what you are doing • Experimenting on an algorithm • Writing utilities and whole programs • What types of m-files are there? • Script m-file: No input and output. Operates on workspace variables. • Function m-file: Contains the functionkey-word, accepts inputs and gives outputs. All variables are local. • Class m-file: Contains the classdefkey-word, used in object oriented programming. Daniel Baur / Introduction to Matlab Part II

  8. Example of a Script • Problem definition • n = 100; v = 1e-17*ones(100,1); sum(v) • v1 = [v;1]; sum(v1)-1 • v2 = [1;v]; sum(v2)-1 • Create the «mysum» script • (In Matlab:) File  New  M-File • n = 100; • v = 1e-17*ones(100,1); • v1 = [v;1]; • s = sum(v1); • s-1 • (In Editor:) File  Save As...  mysum.m • Check the directory path! • Avoid reserved words and built-in function names Daniel Baur / Introduction to Matlab Part II

  9. Example of a Script (Continued) • You should see • How to run the script? • From the command window (check the path!) • From the editor (press Run button or use Debug Run or press F5) The editor has found unusual syntax or even a syntax error here! Mouse-over to see what is the issue. Daniel Baur / Introduction to Matlab Part II

  10. Preventing errors before they happen • The MATLAB editor does (some) on-the-fly proof reading Green = OK No syntax errorsor unusual syntax found Be aware that of course therecan still be semantical errors! Orange = Unusual Syntax The script / function will run, but there are some unusual or subobtimal commands This can be caused by (for example): Not preallocating variables, using variables in an unusual way, overriding variables before they are used even once, etc. Clicking the square and mouse-over works too Red = Syntax Error The script / function will produce and error when run. Click the red square to jump to the error, mouse over the red bar or the underlined part to get some info Daniel Baur / Introduction to Matlab Part III

  11. How to deal with Error Messages in Matlab • The topmost error message is usually the one containing the most useful information • The underlined parts of the message are actually links that you can click to get to the line where the error happened! Daniel Baur / Introduction to Matlab Part III

  12. Relational and Logical Operators • Relational operators are straight forward in Matlab: • <, >, <=, >=, ==, ~= • The NOT operator is the tilde symbol «~» • For the logical operators AND and OR, two kinds exist: • &&, || Operators with short-circuiting (scalars only) • &, | Operators for element-by-element comparisons • Logical operators return logical types • Example of how short-circuitung operators work: In the context of if and while, both kinds of operators short-circuit. Daniel Baur / Introduction to Matlab Part I

  13. Relational and Logical Operators (Continued) • Example of element-by-element comparison: • Compare entire matrices with isequal(A,B) All numbers other than 0 evaluate to TRUE Daniel Baur / Introduction to Matlab Part I

  14. Relational and Logical Operators (Continued) • There are a some more operators that you can use: • any(A,dim); True if at least one element is ≠ 0 • all(A,dim); True if all elements are ≠ 0 • xor(A,B); True if one is = 0 and the other is ≠ 0 • isnumeric(A); True if A is a numerical type • isfinite(A); True for each element if it is neither NaN nor inf • Indexing is possible through logical variable types (try it!) • A(A<0); All elements < 0 • A(isfinite(A)); All elements except NaN and inf • A(A == B); All elements that are equal to their counterpart • You can even edit elements directlythis way Daniel Baur / Introduction to Matlab Part I

  15. For-Loops in Matlab • General form of for-loops: • Example: Daniel Baur / Introduction to Matlab Part II

  16. Examples with loops • Try these: • for i = 0:5:100 iend • v = [0, 4, 5, 11];for i = v iend • n = 1e6; x = rand(n,1);tic; s = 0; for i = 1:n, s = s+x(i)^2; end, s, toctic; s = sum(x.^2); s, toc • Loops are almost always slower than matrix / vector calculations! Daniel Baur / Introduction to Matlab Part II

  17. While-Loops in Matlab • General form of while-loops: • while expression statements;end • The statements are executed as long as the expression is true (or ≠ 0) • The statements are executed an indefinite number of times • It is good practice to limit the number of iterations (eg. while n < nmax) Daniel Baur / Introduction to Matlab Part II

  18. Examples of Loops • Try the following: • clear x; n = 5e4; x(1) = 2; • tic; for i = 2:n; x(i) = x(i-1)+2*i; end, toc • x1 = zeros(1,n); x1(1) = 2; • tic; for i =2:n, x1(i) = x1(i-1)+2*i; end, toc • v = linspace(1,n,n); • tic; x2 = cumsum(v); toc • If you must use a loop, preallocate your variables. • Vectorize your operationsand use built-in functions. Daniel Baur / Introduction to Matlab Part II

  19. Exercise • Create the matrix A(5,5) with random elements between -2 and 2 (read help rand if you cannot figure out how to do it) • Set all negative elements of A to 1.5 • Create a matrix B consisting of the 2nd and 3rd column of A • Create a matrix C consisting of the 1st and 4th row of A • Calculate D = A∙B∙C. What is the size of D? • Add D+A = E. Multiply the transpose of E with B to create F. • Create the matrix G so that Gi,j = 2+2*Ci,j2 / Fj,i • Create an equally spaced row vector b with 5 elements from 3 to 38 • Find the solution of the linear system A∙x = b’ • Find the solution of y∙A = b • Compute the 2-norm of x • Find the vector v representing the 2-norm of each column of A • Find the values of the series Daniel Baur / Introduction to Matlab Part II

  20. Solutions (one Possibility) Daniel Baur / Introduction to Matlab Part II

  21. Controlling Program Flow • The if block has the following structure • if expression statements;elseif expression statements;else statements;end • Example The elseif and else clauses are optional. Daniel Baur / Introduction to Matlab Part II

  22. Controlling Program Flow (Continued) • The switch block does multiple comparisons at once • switch variablecase expression statements;case expression statements; ...otherwise statements;end • Example Message identifier Error message Daniel Baur / Introduction to Matlab Part II

  23. Controlling Program Flow (Continued) • Other commands for controlling program flow are: • break; Exits the current loop • continue; Immediately goes to the next iteration • return; Terminates the entire program / function Daniel Baur / Introduction to Matlab Part II

  24. Controlling Program Flow (Continued) • The try block checks for errors occuring during execution • try statements;catch err statements;end • If an error occurs in the try block, the catch block is executed immediately instead of continuing • Example Daniel Baur / Introduction to Matlab Part II

  25. Data Type «struct» • What is a struct? • Structs are arrays with a property called «fields». Fields hold different kinds of data and are accessed by dots. Structs are very useful for bundling different kinds of information. • Example (try it out!) comp(1).name = 'water';comp(1).Mw = 18.02;comp(1).density = 1;comp(2).name = 'ethanol';comp(2).Mw = 46.06;comp(2).density = 0.789; Daniel Baur / Introduction to Matlab Part II

  26. Data Type «function_handle» • What is a function handle? • Function handles put a function into a variable • @() is used to define function handles • Putting a variable name into the parentheses after the @ tells MATLAB: «All that comes now is a function of this variable!» • Example • Consider the function f(x) = cos(x) – 2 • Try:f = @(x) cos(x) – 2;a = f(pi) • Functions of multiple variables are also possible:g = @(x,y) cos(x) + sin(y) + a;b = g(2,3) Daniel Baur / Introduction to Matlab Part II

  27. Exercise • Create a new m-file called quadratic_roots.m • Implement the following algorithm • If b > 0 • Elseif b < 0 • Else Daniel Baur / Introduction to Matlab Part II

  28. Possible Solution Daniel Baur / Introduction to Matlab Part II

More Related