Chapter 5. Loops are common in most programming languages Plus side: Are very fast (in other languages) & easy to understand Negative side: Require a.

Slides:



Advertisements
Similar presentations
Lecture 5.
Advertisements

Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
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.
Chapter Chapter 4. Think back to any very difficult quantitative problem that you had to solve in some science class How long did it take? How many times.
Chapter 4 Systems of Linear Equations; Matrices Section 2 Systems of Linear Equations and Augmented Matrics.
Chapter 1 Computing Tools Data Representation, Accuracy and Precision Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction.
Lesson 8 Gauss Jordan Elimination
Lecture 4 Sept 8 Complete Chapter 3 exercises Chapter 4.
CIS 101: Computer Programming and Problem Solving Lecture 2 Usman Roshan Department of Computer Science NJIT.
Lecture 7 Sept 19, 11 Goals: two-dimensional arrays (continued) matrix operations circuit analysis using Matlab image processing – simple examples Chapter.
Lecture 6 Sept 15, 09 Goals: two-dimensional arrays matrix operations circuit analysis using Matlab image processing – simple examples.
Concatenation MATLAB lets you construct a new vector by concatenating other vectors: – A = [B C D... X Y Z] where the individual items in the brackets.
Lecture 4 Sept 7 Chapter 4. Chapter 4 – arrays, collections and indexing This chapter discusses the basic calculations involving rectangular collections.
Dr. Jie Zou PHY Welcome to PHY 3320 Computational Methods in Physics and Engineering.
Matrix Mathematics in MATLAB and Excel
Arithmetic Operations on Matrices. 1. Definition of Matrix 2. Column, Row and Square Matrix 3. Addition and Subtraction of Matrices 4. Multiplying Row.
Chapter 7 Matrix Mathematics Matrix Operations Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
Algebra 2: Lesson 5 Using Matrices to Organize Data and Solve Problems.
MATLAB FUNDAMENTALS: INTRO TO LINEAR ALGEBRA NUMERICAL METHODS HP 101 – MATLAB Wednesday, 11/5/2014
ECON 1150 Matrix Operations Special Matrices
Matlab tutorial course Lesson 2: Arrays and data types
Array Math.
Solving Systems of Equations by matrices
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
1 Week 3: Vectors and Matrices (Part III) READING: 2.2 – 2.4 EECS Introduction to Computing for the Physical Sciences.
Array Addition  Two arrays can be added if and only if both arrays have exactly the same dimensions.  Assuming the dimension requirement is satisfied,
259 Lecture 13 Spring 2013 Advanced Excel Topics – Arrays.
Matrix Arithmetic. A matrix M is an array of cell entries (m row,column ) and it must have rectangular dimensions (Rows x Columns). Example: 3x x.
13.1 Matrices and Their Sums
1 Chapter 3 Arrays (2) 1. Array Referencing 2. Common Operations 1. Slicing 2. Diminution 3. Augmentation 3. List of Commonly Used Built-in Functions 1.
Arrays 1 Multiple values per variable. Why arrays? Can you collect one value from the user? How about two? Twenty? Two hundred? How about… I need to collect.
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.
If A and B are both m × n matrices then the sum of A and B, denoted A + B, is a matrix obtained by adding corresponding elements of A and B. add these.
Lesson 11-1 Matrix Basics and Augmented Matrices Objective: To learn to solve systems of linear equation using matrices.
MA/CS 375 Fall 2002 Lecture 3. Example 2 A is a matrix with 3 rows and 2 columns.
A string is an array of characters Strings have many uses in MATLAB Display text output Specify formatting for plots Input arguments for some functions.
CS 170 – INTRO TO SCIENTIFIC AND ENGINEERING PROGRAMMING.
Matrices and Systems of Linear Equations
Matrices: Simplifying Algebraic Expressions Combining Like Terms & Distributive Property.
Multiplying Matrices Algebra 2—Section 3.6. Recall: Scalar Multiplication - each element in a matrix is multiplied by a constant. Multiplying one matrix.
MA/CS 375 Fall 2003 Lecture 3. .* Multiplication We can use the.* operator to perform multiplication entry by entry of two matrices:
MATRICES MATRIX OPERATIONS. About Matrices  A matrix is a rectangular arrangement of numbers in rows and columns. Rows run horizontally and columns run.
Sec 4.1 Matrices.
Algebra Matrix Operations. Definition Matrix-A rectangular arrangement of numbers in rows and columns Dimensions- number of rows then columns Entries-
MA/CS 375 Fall 2002 Lecture 2. Motivation for Suffering All This Math and Stuff Try the Actor demo from
Array Accessing and Strings ENGR 1187 MATLAB 3. Today's Topics  Array Addressing (indexing)  Vector Addressing (indexing)  Matrix Addressing (indexing)
Improving Matlab Performance CS1114
Systems of Equations and Matrices Review of Matrix Properties Mitchell.
Computer Graphics Mathematical Fundamentals Lecture 10 Taqdees A. Siddiqi
Matrices. Matrix - a rectangular array of variables or constants in horizontal rows and vertical columns enclosed in brackets. Element - each value in.
If A and B are both m × n matrices then the sum of A and B, denoted A + B, is a matrix obtained by adding corresponding elements of A and B. add these.
A rectangular array of numeric or algebraic quantities subject to mathematical operations. The regular formation of elements into columns and rows.
Chapter 7 Matrix Mathematics
Matrix Operations.
Matrix Operations Monday, August 06, 2018.
Multiplying Matrices Algebra 2—Section 3.6.
Warm Up Use scalar multiplication to evaluate the following:
Multiplying Matrices.
Vectors and Matrices Chapter 2 Attaway MATLAB 4E.
Vectorized Code, Logical Indexing
MATRICES MATRIX OPERATIONS.
Loop Statements & Vectorizing Code
Vectors and Matrices Chapter 2 Attaway MATLAB 4E.
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.
Multiplying Matrices.
Loop Statements & Vectorizing Code
Multiplying Matrices.
Multiplying Matrices.
Multiplying Matrices.
Presentation transcript:

Chapter 5

Loops are common in most programming languages Plus side: Are very fast (in other languages) & easy to understand Negative side: Require a lot of code Loops in MATLAB are not so fast MATLAB provides a ton of ways to avoid using loops For most problems (< 1e6 data, or so), loops are fast enough Vectorizing: The process of converting what would normally be done in a loop to use array operations, and/or built-in MATLAB functions The plus side: Code runs faster. Often easier to write The negative side: All of this ONLY works in MATLAB

Lets mimic the behavior of the MATLAB function “sum” Use a for loop Which is faster? The loop The built-in sum function Why is the sum function provided?

Use tic toc to time each method for summing numbers Both give the same answer

Use tic toc to time each method for summing numbers Both give the same answer

Matrix Addition/Subtraction Both must have same dimensions Add each pair of corresponding elements Result has same dimensions Can add a scalar to a matrix Would require a loop in most programming languages Is automatic in MATLAB Called a “scalar operation” Adds scalar to each element

Matrix Multiplication/Division If A is 3x2 and B is 2x3 [ 3 x 2 ] * [ 2 x 3 ] Red box: must be equal Blue box: Result is 3x3 Can multiply a matrix by a scalar Would require a loop in most programming languages Is automatic in MATLAB Called a “scalar operation” Multiplies each element by the scalar

Say you wanted to multiply each entry in one matrix by a corresponding value in another matrix In most programming languages, this would require a loop In MATLAB, you can use an array operation * = matrix multiplication.* = array multiplication

100 million temp measurements in °F Convert to °F Plots results to see if results are the same

100 million temp measurements in °F Convert to °F Plots results to see if results are the same

100 million temp measurements in °F Convert to °F Plots results to see if results are the same

Add 4 to all entries in a vector How could we re-write this without using the loop? Scalar operation!

Multiply entries of two matrices together How could we re-write this without using the loop? Use an array operation!

Grab and store a column from a matrix How could we re-write this without using the loop?

What about function arguments? Functions should be written to handle either scalars or matrices/vectors

What about function arguments? Functions should be written to handle either scalars or matrices/vectors How can we get rid of the for loop?

What about function arguments? Functions should be written to handle either scalars or matrices/vectors Now it is vectorized! Built-in MATLAB functions work just like this sin, cos, tan, sum, max, min, etc…

Can we vectorize conditional statements? Yes! Recall that MATLAB offers a variable type called “logical” Can only have two values 0 = False 1 = True

When converted to logical… Any non-zero number 1 (true) Any zero number 0 (false) You can perform mathematical operations on logical values, but they are automatically converted to doubles

We can convert vectors of any numeric type to logical vectors Any non-zero entry 1 (true) Any zero entry 0 (false) You can index a vector by using a logical vector Only entries with non-zero entries are kept

We can convert matrices of any numeric type to logical matrices Any non-zero entry 1 (true) Any zero entry 0 (false) You can index a matrix by using a logical vector Only entries with non-zero entries are kept Matrix is unwrapped and returned as a vector Why?

Why does C not do what you expect? The variable doing the indexing must of class=logical

Using logical vectors, we can vectorize conditional statements that would normally require a loop

How can I test only one column?

Loops through “dat” Stores all values > 3 in “newDat”

Loops through “dat” Stores all values > 3 in “newDat”

Finds: Vals > 5 in col 1 Vals < 5 in col 2 Prints times

Vectorized Code wins again

MATLAB provides several built-in functions that perform logical tests all, any, find, sign You can read the documentation for “all”, “any”, and “sign” Lets look at what find does Returns the linear index of all values that satisfy some condition

MATLAB provides a clever function that calculates differences in adjacent data entries. “diff” Is VERY useful for calculating approximate derivatives Input matrix length=n Output matrix length=n-1

Diff can also accept matrices as arguments Returns the differences of successive rows

Recall that a derivative is just a slope Exact analytical derivatives are only possible for algebraic equations For data, we cannot calculate exact analytical derivatives We can calculate slopes! Same is true for integrals. We calculate areas under datasets. Why do I not need to calculate diff(x) in this case? Why do I not need to calculate diff(x) in this case?

“diff” can also calculate 2 nd, 3 rd, or n th derivatives Lose one data point per derivative

“diff” can also calculate approximate second or n th derivatives “diff” can also calculate approximate second or n th derivatives Note that each time you use diff, you lose one data pointNote that each time you use diff, you lose one data point Where (at what x location) should second derivatives be plotted?Where (at what x location) should second derivatives be plotted?

A common task in quantitative science is to evaluate 2D or 3D spatial equations. To do this, you need a 2D or 3D grid of (x,y,z) data points In most programming languages: nested for loops In MATLAB: nested for loops, or the built-in function “meshgrid” Lets flashback to the Loops lecture notes… 3D image of a carbonate reef

This is NOT the way to do it! Lets try a nested for loop

To make a 2D grid we need a nested for loop Outer loop: x-range; Inner loop: y-range Could even make spherical grids (r, θ, ϕ)

To make a 2D grid we can also use the efficient built-in function “meshgrid” meshgrid will return: 3 matrices for 3D 2 matrices for 2D You must specify where to store all matrices, or you only get one!

meshgrid returns rectangular matrices Often, we want data in columns Col 1: X-Values; Col 2: Y-Values Use “reshape” to get in cols

meshgrid can also make 3D grids! Returns 3D matrices (refer to CH1 in Attaway & lecture notes)

Meshgrid will also accept ranges using the “linspace” function

MATLAB is a bit of an unusual programming language Most languages rely heavily on loops So, anyone that knows how to code, knows loops well In MATLAB: You can use loops (a little on the slow side) You can avoid loops using vectorized code What is best? If data set is small (less than millions of points) Do whichever you prefer, or is easier to write/understand If data set is large or computation time is an issue Use vectorized code, and built-in functions (when possible)