Introduction to Matlab Part II 1Daniel Baur / Introduction to Matlab Part II Daniel Baur / Michael Sokolov ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften.

Slides:



Advertisements
Similar presentations
Programming Tips: While Loops and Comparisons 1Daniel Baur / Numerical Methods for Chemical Engineerse Daniel Baur ETH Zurich, Institut für Chemie- und.
Advertisements

Fixed point iterations and solution of non-linear functions
Introduction to Matlab
Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
MATLAB – What is it? Computing environment / programming language Tool for manipulating matrices Many applications, you just need to get some numbers in.
Slide deck by Dr. Greg Reese Miami University MATLAB An Introduction With Applications, 5 th Edition Dr. Amos Gilat The Ohio State University Chapter 3.
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Systems of Linear Equations
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Computer Science in Practice This course is an introduction to problems (and solutions) that arise in applied fields of computer science such as machine.
Introduction to MATLAB
Computer Science in Practice This course is an introduction to problems (and solutions) that arise in applied fields of computer science such as machine.
Introduction to Matlab 7 Part I 1Daniel Baur / Introduction to Matlab Part I Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften.
C ENTER FOR I NTEGRATED R ESEARCH C OMPUTING MATLAB
Matrix Mathematics in MATLAB and Excel
1 Chapter 3 Matrix Algebra with MATLAB Basic matrix definitions and operations were covered in Chapter 2. We will now consider how these operations are.
Introduction to programming in MATLAB MATLAB can be thought of as an super-powerful graphing calculator Remember the TI-83 from calculus? With many more.
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
1 MATLAB 基礎. 2 MATLAB  Workspace: environment (address space) where all variables reside  After carrying out a calculation, MATLAB assigns the result.
Chapter 10 Review: Matrix Algebra
Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften.
Matlab tutorial course Lesson 2: Arrays and data types
Martin Ellison University of Warwick and CEPR Bank of England, December 2005 Introduction to MATLAB.
Engineering Analysis ENG 3420 Fall 2009 Dan C. Marinescu Office: HEC 439 B Office hours: Tu-Th 11:00-12:00.
Nonparametric Econometrics1 Intro to Matlab for Data Analysis and Statistical Modeling.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
Introduction to Matlab 1. Outline: What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators Plotting Flow Control Using of M-File Writing.
Introduction to MATLAB. Windows in MATLAB Command Window – where you enter data, run MATLAB code, and display results Command History - displays a log.
CSE123 Lecture 5 Arrays and Array Operations. Definitions Scalars: Variables that represent single numbers. Note that complex numbers are also scalars,
Array Addition  Two arrays can be added if and only if both arrays have exactly the same dimensions.  Assuming the dimension requirement is satisfied,
1 Lab of COMP 406 Teaching Assistant: Pei-Yuan Zhou Contact: Lab 1: 12 Sep., 2014 Introduction of Matlab (I)
Matlab Programming, part 1 M-files It is generally more convenient to program in Matlab using m-files, ascii text files containing a set of Matlab commands.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
Boundary Value Problems and Least Squares Minimization
CMPS 1371 Introduction to Computing for Engineers MATRICES.
Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011.
1 Lab 2 of COMP 319 Lab tutor : Shenghua ZHONG Lab 2: Sep. 28, 2011 Data and File in Matlab.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Intro to Matlab 1.Using scalar variables 2.Vectors, matrices, and arithmetic 3.Plotting 4.Solving Systems of Equations Can be found at:
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Introduction to MATLAB Session 1 Simopekka Vänskä, THL 2010.
OUTLINE Overview Numbers, variables and similar in Matlab
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Array Operations ENGR 1181 MATLAB 4.
Digital Image Processing Introduction to M-function Programming.
Introduction to Matlab Electromagnetic Theory LAB by Engr. Mian Shahzad Iqbal.
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
1 Lecture 3 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
Introduction to Matlab Patrice Koehl Department of Biological Sciences National University of Singapore
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
Intro to Matlab Yipei Wang & Qihui Li {yipeiw,
Introduction to Programming on MATLAB Ecological Modeling Course Sep 11th, 2006.
CS100A, Fall 1998, Lecture 201 CS100A, Fall 1998 Lecture 20, Tuesday Nov 10 More Matlab Concepts: plotting (cont.) 2-D arrays Control structures: while,
L – Modeling and Simulating Social Systems with MATLAB
Scripts & Functions Scripts and functions are contained in .m-files
Matlab Workshop 9/22/2018.
Introduction to MATLAB
StatLab Matlab Workshop
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
Matlab tutorial course
CS 175 Project in AI Discussion -- matlab
Announcements P3 due today
Presentation transcript:

Introduction to Matlab Part II 1Daniel Baur / Introduction to Matlab Part II Daniel Baur / Michael Sokolov ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften ETH Hönggerberg / HCI F128 / F123 – Zürich

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

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

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

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  D*C Not commutative!  A^2 Element-by-element operations  A.^2  E = 2.^A;  E = 2.^A; E i,j = 2^A i,j  sqrt(A) Functions using matrices  sqrtm(A)  sqrtm(A)^2  inv(A) 5Daniel Baur / Introduction to Matlab Part II

Review of matrix operations (continued)  Matrix properties  sum(A,dim);  det(A);  inv(A);  eigs(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; 6Daniel Baur / Introduction to Matlab Part II Do not use x = inv(A)*b!

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  Function m-file: Starts with the function key-word, accepts inputs and gives outputs. All variables are local. classdef  Class m-file: Contains the classdef key-word, used in object oriented programming. 7Daniel Baur / Introduction to Matlab Part II

Example of a Script  Problem definition  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  clear all; close all;  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! 8Daniel Baur / Introduction to Matlab Part II Avoid reserved words and built-in function names

 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) Example of a Script (Continued) 9Daniel Baur / Introduction to Matlab Part II The editor has found unusual syntax or even a syntax error here! Mouse-over to see what is the issue. The editor has found unusual syntax or even a syntax error here! Mouse-over to see what is the issue.

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: 10Daniel Baur / Introduction to Matlab Part I In the context of if and while, both kinds of operators short-circuit.

Relational and logical operators (continued)  Example of element-by-element comparison: isequal(A,B)  Compare entire matrices with isequal(A,B) 11Daniel Baur / Introduction to Matlab Part I All numbers other than 0 evaluate to TRUE

Relational and logical Operators (continued)  There are a some more operators that you can use:  any(A,dim);  any(A,dim); True if at least one element is ≠ 0  all(A,dim);  all(A,dim); True if all elements are ≠ 0  xor(A,B);  xor(A,B); True if one is = 0 and the other is ≠ 0  isnumeric(A);  isnumeric(A); True if A is a numerical type  isfinite(A);  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);  A(A<0); All elements < 0  A(isfinite(A));  A(isfinite(A)); All elements except NaN and inf  A(A == B);  A(A == B); All elements that are equal to their counterpart  You can even edit elements directly this way 12Daniel Baur / Introduction to Matlab Part I

For-loops in Matlab  General form of for-loops:  Example: 13Daniel Baur / Introduction to Matlab Part II If Matlab gets stuck in a loop (or any other calculation), use ctrl+c to terminate the program.

Examples with for-loops  Try these: 14Daniel Baur / Introduction to Matlab Part II Loops are almost always slower than matrix / vector calculations!

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 15Daniel Baur / Introduction to Matlab Part II It is good practice to limit the number of iterations (eg. while n < nmax)

Examples of loops  Try the following: 16Daniel Baur / Introduction to Matlab Part II Vectorize your operations and use built-in functions. If you must use a loop, preallocate your variables.

Exercise help rand 1.Create the matrix A(5,5) with random elements between -2 and 2 (type help rand to figure out how the function works) 2.Set all negative elements of A to 1.5 (use logical indexing!) 3.Create a matrix B consisting of the 2 nd and 3 rd column of A 4.Create a matrix C consisting of the 1 st and 4 th row of A 5.Calculate D = A∙B∙C. What is the size of D? 6.Add D+A = E. Multiply the transpose of E with B to create F. 7.Create the matrix G so that G i,j = 2+2*C i,j 2 / F j,i 8.Create an equally spaced row vector b with 5 elements from 3 to 38 9.Find the solution of the linear system A∙x = b’ 10.Find the solution of y∙A = b 11.Compute the 2-norm of x 12.Find the vector v representing the 2-norm of each column of A 13.Find the values of the series 17Daniel Baur / Introduction to Matlab Part II

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

Controlling program flow  The if block has the following structure  if expression statements; elseif expression statements; else statements; end  Example 19Daniel Baur / Introduction to Matlab Part II The elseif and else clauses are optional.

Controlling program flow (Continued)  The switch block does multiple comparisons at once  switch variable case expression statements; case expression statements;... otherwise statements; end  Example 20Daniel Baur / Introduction to Matlab Part II Message identifier Error message

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

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 22Daniel Baur / Introduction to Matlab Part II

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; 23Daniel Baur / Introduction to Matlab Part II

Data type «struct» 24Daniel Baur / Introduction to Matlab Part II comp(1).name = 'water'.MW = density= 1.Antoine= [8.07; 1730; 233]; comp(2).name = 'ethanol'.MW = density= Antoine= [8.20; 1643; 230]; comp(3).name =....MW =....density=....Antoine=... comp(1,n)struct

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

Possible Solution 26Daniel Baur / Introduction to Matlab Part II