ENGG1811 Computing for Engineers Week 10 Matlab: Vectorization. (No loops, please!)

Similar documents
7 Control Structures, Logical Statements

Ch.5. Loops. (a.k.a. repetition or iteration)

Vectors and Matrices. Chapter 2. Linguaggio Programmazione Matlab-Simulink (2017/2018)

MATH-680: Mathematics of genome analysis Introduction to MATLAB

Repetition Structures Chapter 9

Getting started with MATLAB

Introduction and MATLAB Basics

Introudction to Computation and Cognition 2015 Dr. Oren Shriki Shay Ben-Sasson, Ofer Groweiss. MATLAB tutorial

.

A. Incorrect! This would be the negative of the range. B. Correct! The range is the maximum data value minus the minimum data value.

ENGR 1181 MATLAB 09: For Loops 2

MAT 343 Laboratory 1 Matrix and Vector Computations in MATLAB

Introduction to R. Stat Statistical Computing - Summer Dr. Junvie Pailden. July 5, Southern Illinois University Edwardsville

Quadratic: the time that it takes to sort an array is proportional to the. square of the number of elements.

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

Control Structures. March 1, Dr. Mihail. (Dr. Mihail) Control March 1, / 28

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.

Introduction to Matlab

LAB 2 VECTORS AND MATRICES

Introduction to MATLAB. CS534 Fall 2016

MATLAB: The Basics. Dmitry Adamskiy 9 November 2011

Vectorization: An Introduction. Dr. Marco A. Arocha INGE3016-MATLAB Summer 2015

ECE 122. Engineering Problem Solving with Java

TUNING MATLAB FOR BETTER PERFORMANCE. Keith Ma Boston University Research Computing Services

Computer Programming ECIV 2303 Chapter 6 Programming in MATLAB Instructor: Dr. Talal Skaik Islamic University of Gaza Faculty of Engineering

Financial Econometrics MFE MATLAB Introduction. Kevin Sheppard University of Oxford

EGR 102 Introduction to Engineering Modeling. Lab 10A Nested Programming II Iterative Nesting

Introduction to Matlab

COMP108 Algorithmic Foundations

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

Vector: A series of scalars contained in a column or row. Dimensions: How many rows and columns a vector or matrix has.

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

Programming for Experimental Research. Flow Control

Array Accessing and Strings ENGR 1181 MATLAB 3

MATLAB GUIDE UMD PHYS401 SPRING 2011

COMP108 Algorithmic Foundations

Flow Control. Statements We Will Use in Flow Control. Statements We Will Use in Flow Control Relational Operators

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

One-dimensional Array

SECTION 2: PROGRAMMING WITH MATLAB. MAE 4020/5020 Numerical Methods with MATLAB

Data Frames and Control September 2014

Lecture 57 Dynamic Programming. (Refer Slide Time: 00:31)

9/4/2018. Chapter 2 (Part 1) MATLAB Basics. Arrays. Arrays 2. Arrays 3. Variables 2. Variables

ENGG1811 Computing for Engineers Week 6 Iteration; Sequential Algorithms; Processing Cells

Introduction to MATLAB. Simon O Keefe Non-Standard Computation Group

Memory Management. Disclaimer: some slides are adopted from book authors slides with permission 1

ENGG1811: Data Analysis using Spreadsheets Part 1 1

CS 221 Lecture. Tuesday, 11 October 2011

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

1 Matrices and Vectors and Lists

MATLAB TUTORIAL WORKSHEET

General Instructions. Questions

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

Stokes Modelling Workshop

INTRODUCTION OF LOOPS

STA 570 Spring Lecture 5 Tuesday, Feb 1

Statistical Computing (36-350)

SECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing

Getting Started with MATLAB

Introduction. Matlab for Psychologists. Overview. Coding v. button clicking. Hello, nice to meet you. Variables

CEMTool Tutorial. Control statements

CS 221 Lecture. Tuesday, 4 October There are 10 kinds of people in this world: those who know how to count in binary, and those who don t.

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

Solving Equations with Inverse Operations

2.2 (a) Statement, subroutine, procedure, function, parameter, loop

Introduction to R. Course in Practical Analysis of Microarray Data Computational Exercises

EGR 111 Loops. This lab is an introduction to loops, which allow MATLAB to repeat commands a certain number of times.

Introduction to Matlab

Array Accessing and Strings ENGR 1187 MATLAB 3

Computer Laboratory. Exercises in LINEAR PROGRAMMING AND COMBINATORIAL OPTIMIZATION

MAT 343 Laboratory 1 Matrix and Vector Computations in MATLAB

Fundamental Programming Principles: Variables and Func6ons

function [s p] = sumprod (f, g)

AN INTRODUCTION TO MATLAB

C/C++ Programming for Engineers: Matlab Branches and Loops

ECE 102 Engineering Computation

Getting started with MATLAB

Weka ( )

Is the statement sufficient? If both x and y are odd, is xy odd? 1) xy 2 < 0. Odds & Evens. Positives & Negatives. Answer: Yes, xy is odd

Principles of Programming. Chapter 6: Arrays

Introduction to Matlab. By: Hossein Hamooni Fall 2014

Matrices. A Matrix (This one has 2 Rows and 3 Columns) To add two matrices: add the numbers in the matching positions:

An Introduction to Matlab for DSP

DSC 201: Data Analysis & Visualization

STATISTICS 579 R Tutorial : Programming in R

1 Built-In Math Functions

Government Polytechnic Muzaffarpur.

CS4023 Week06 Lab Exercise

MATH (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab

MATLAB GUIDE UMD PHYS375 FALL 2010

MATLAB Tutorial. Mohammad Motamed 1. August 28, generates a 3 3 matrix.

Attia, John Okyere. Control Statements. Electronics and Circuit Analysis using MATLAB. Ed. John Okyere Attia Boca Raton: CRC Press LLC, 1999

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Colorado State University Department of Mechanical Engineering. MECH Laboratory Exercise #1 Introduction to MATLAB

1. Register an account on: using your Oxford address

PART 1 PROGRAMMING WITH MATHLAB

Deep Learning for Visual Computing Prof. Debdoot Sheet Department of Electrical Engineering Indian Institute of Technology, Kharagpur

LECTURE 1. What Is Matlab? Matlab Windows. Help

EGR 111 Introduction to MATLAB

Matlab course at. P. Ciuciu 1,2. 1: CEA/NeuroSpin/LNAO 2: IFR49

Transcription:

ENGG1811 Computing for Engineers Week 10 Matlab: Vectorization. (No loops, please!) ENGG1811 UNSW, CRICOS Provider No: 00098G1 W10 slide 1

Vectorisation Matlab is designed to work with vectors and matrices efficiently Many calculations that required loops in many programming languages (e.g. OpenOffice Basic) can be done without any loops in Matlab This is called vectorisation ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 2

Comparing three methods We want to compute the cube roots of all the elements in the vector v with 1,000,001 elements v = 0 : 0.1 : 100000 We will compare 3 methods to do this All three methods are correct but they take different amount of time to complete the work ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 3

Method 2: for-loop, allocate storage The code is: cuberoot2 = zeros(size(v)); % allocate storage for the answer for idx = 1:length(v) cuberoot2(idx) = v(idx) ^ (1/3); end The first statement tells Matlab to reserve memory space to store 1,000,001 numbers Key feature of this method: Allocate memory space to store the answer ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 4

Method 1: for-loop; does not allocate storage The method is the same as method 2 except it does not allocate storage space in the beginning. The code is: for idx = idx = 1:length(v) cuberoot1(idx) = v(idx) ^ (1/3); End The length of the array cuberoot1 is increased by one per iteration. 1 st iteration: cuberoot1 has a length of 1 2 nd iteration: cuberoot1 has a length of 2 3 rd iteration: cuberoot1 has a length of 3 etc. ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 5

Method 3: using array operation.^ The code is: cuberoot3 = v.^ (1/3); Recall there are two aspects to algorithms Correctness and efficiency All 3 methods are correct But they have different efficiency ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 6

Compare the three methods The program is in the file comparemethods.m It uses Matlab built-in functions clock and etime to determine how long each method takes timestart = clock; % get the time before the computation starts (code block that you want to measure the computation time) timeneeded = etime(clock,timestart); % time elasped between current time (given by clock) and the % start time (stored in timestart) % etime is short for elapsed time ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 7

Lesson 1: Allocate storage For faster computation, initialise the storage space for arrays This is especially important for big matrices You can do that by initializing a zero matrix at first and then fill in the elements later on, e.g. cuberoot2 = zeros(size(v)); % allocate storage for the answer If you don t know what the size of the matrix should be, do an over-estimation and reduce the size of it later This is what you do in Lab10 ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 8

Why is it slow if you don t allocate storage? The following gives you 1:100 but is slow v = []; for k = 1:100 v = [v k]; % Length of vector v increased by 1 at each iteration end For explanation, consider v = [1 2 3] To add a 4 to v, Matlab needs to 1) Find a memory space to store a vector with 4 elements Old memory location New memory location 1 2 3 1 2 3 4 2) Copy [1 2 3] to new memory location 3) Add 4 Time is wasted on these processes! ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 9

Lesson 2 + one other tip Array operation is faster than for-loops. Use array operation whenever possible. If there is a built-in function that does what you want, use it because it is normally faster Many useful functions use vectorisation You can find a list of functions that commonly used in vectorisation here: http://www.mathworks.com.au/help/matlab/ matlab_prog/vectorization.html ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 10

Some useful functions sum cumsum : cumulative sum std : standard deviation var : variance prod: product mean median max, min mode: most frequently occurred value sort Note: These functions work differently for vectors and matrices. The idea is similar, so we use sum as an illustration Some functions can take additional inputs or return more than one output. Check the documentation for details. ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 11

The sum function (1) v1 = [1 2 3]; v2 = [- 1 ; - 2 ; 4]; % row vector % column vector >> sum(v1) 6 >> sum(v2) 1 sum(a one dimensional array) is a scalar ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 12

The sum function (2) m = [1 2 3 ; 4 5 6]; % a 2-by-3 array >> sum(m,1) % sum in 1st dimension (sum the rows) 5 7 9 % Note sum(m) is the same as sum(m,1) >> sum(m,2) % sum in 2nd dimension (sum the columns) 6 15 % = sum(m. ) [ 1 2 3 ] 4 5 6 (row index, column index) 1 st dim 2 nd dim ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 13

m = [1 2 3 ; 4 5 6]; >> sum(sum(m)) Quiz: The sum function Question: How do you sum all the elements of a matrix? total = 0; for ii = 1:size(m,1) for jj = 1:size(m,2) total = total + m(ii,jj); end end In other programming languages, a nested forloop is required. ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 14

Logical arrays z = [1 2 3; 4 5 6; 7 8 9]; b = z > 5; % b is a logical array, containing 1 and 0 % 1 represents TRUE, 0 represents FALSE b = 0 0 0 0 0 1 1 1 1 Operations on logical arrays & is the element-wise and operator is the element-wise or operator ~ is the negation operator Note: && is the scalar and is the scalar or They are in fact short-circuit operators next week ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 15

Example: Logical arrays (Slide 1) Sometimes what you want to do is not the same for every element, but depends on its value Example: replace all negative values in an array by zero, and square the positive ones If you use loops, this is what you would write. for idx = 1:length(v) if v(idx) < 0 v(idx) = 0 else v(idx) = v(idx)^2 end end ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 16

Example: Logical arrays (Slide 2) You can use logical arrays to select elements in an array The two arrays must have the same size isneg = v < 0; % isneg is a logical array the same size as v v(isneg) = 0; % true values select which subscripts v(~isneg) = v(~isneg).^ 2; % ~ is the not operator Demo ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 17

Matlab function: find Amongst the many useful Matlab functions is find, which can be used to locate elements of an array that meet a set of criteria, returning their indexes: >> x = [3, - 4, 0, 1.23, 17, 0, - 2, 0]; % 1 2 3 4 5 6 7 8 (indexes) >> find(x) % default: find non- zero values ans = 1 2 4 5 7 >> find(x<0) % negative values ans = 2 7 ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 18

Matlab function: find (More examples) (1) >> x = [3, - 4, 0, 1.23, 17, 0, - 2, 0]; % 1 2 3 4 5 6 7 8 (indexes) >> find(x<0, 1, 'last') % the last n matches (1) ans = 7 >> find(x==0, 2, 'first') % the first n matches (2) ans = 3 6 ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 19

Matlab function: find (Quiz) >> x = [3, - 4, 0, 1.23, 17, 0, - 2, 0]; % 1 2 3 4 5 6 7 8 (indexes) >> find( (x > 1) & (x < 10) ) ans = 1 4 >> find( (x < 1) (x > 10) ) ans = 2 3 5 6 7 8 ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 20

Example: find Example: replace all negative values in an array by zero, and square the positive ones We can also solve this problem with find indicesneg = find(v < 0); v(indicesneg) = 0; indicesnonneg = find(v >= 0); v(indicesnonneg) = v(indicesnonneg).^2 ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 21

Quiz How can you find the number of elements in a vector that is > 5? Method 1: Using logical array Method 2: Using find sum(w > 5) length(find(w > 5)) ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 22

Example: diff Example: diff computes the difference between consecutive elements y = [4-1 5 6 2]; diff(y) ans = - 5 6 1-4 y(2)-y(1) y(3)-y(2) For a vector v with length n, diff(v) has a length of n-1. More options, see documentation. ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 23

Matlab functions: all, any For a vector v, any(v) returns a 1 if there is at least one non-zero element in v all(v) returns a 1 if all the elements are non-zero For matrices m, any(m,1), any(m,2), all(m,1), all(m,2) Default: any(m,1) is any(m) etc. Same principle as sum ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 24

Exercise A pedometer is used to count the number of steps that a person has walked. A method to count the number of steps is to count the number of cycles. One method to count the number of cycles is to count the number of times the acceleration crosses the zero level and is increasing. ENGG1811 UNSW, CRICOS Provider No: 00098G W8 slide 25

Illustration of rising zero-crossings ENGG1811 UNSW, CRICOS Provider No: 00098G W8 slide 26

Data Load the file walkacc.txt into Matlab The variable name will be walkacc The file contains acceleration data 1492 rows and 3 columns Each row is a sampling instance The 3 columns, corresponding to the acceleration in the x-, y- and z-directions ENGG1811 UNSW, CRICOS Provider No: 00098G W8 slide 27

Questions 1. For each sampling instance, compute the net acceleration: q a 2 x + a 2 y + a 2 z 1 where a x is the acceleration in x-direction etc. The results should be stored in a vector. 2. Compute the number of rising zero-crossings 3. Compute the number of zero-crossings You are asked to complete each of the above tasks with only one line of Matlab code. You can complete your work in pedometer_prelim.m ENGG1811 UNSW, CRICOS Provider No: 00098G W8 slide 28

2 6 4 Question 1: illustration a(1, 1) a(1, 2) a(1, 3) a(2, 1) a(2, 2) a(2, 3) a(3, 1) a(3, 2) a(3, 3)......... 3 7 5 2 6 4 p a(1, 1)2 + a(1, 2) 2 + a(1, 3) 2 1 p a(2, 1)2 + a(2, 2) 2 + a(2, 3) 2 1 p a(3, 1)2 + a(3, 2) 2 + a(3, 3) 2 1... 3 7 5 ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 29

Questions 2 and 3: illustration Assume that the net acceleration is stored in a vector a net acceleration a(5) a(4) a(6) time a(3) a(7) a(2) a(8) a(1) ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 30

2 6 4 Question 1 (Breaking down to small steps) (1) a(1, 1) a(1, 2) a(1, 3) a(2, 1) a(2, 2) a(2, 3) a(3, 1) a(3, 2) a(3, 3)... 3 7 5 2 6 4 Final outcome: p a(1, 1)2 + a(1, 2) 2 + a(1, 3) 2 1 p a(2, 1)2 + a(2, 2) 2 + a(2, 3) 2 1 p a(3, 1)2 + a(3, 2) 2 + a(3, 3) 2 1. 3 7 5 2 6 4 a(1, 1) 2 a(1, 2) 2 a(1, 3) 2 a(2, 1) 2 a(2, 2) 2 a(2, 3) 2 a(3, 1) 2 a(3, 2) 2 a(3, 3) 2... 3 7 5 2 6 4 a(1, 1) 2 + a(1, 2) 2 + a(1, 3) 2 a(2, 1) 2 + a(2, 2) 2 + a(2, 3) 2 a(3, 1) 2 + a(3, 2) 2 + a(3, 3) 2. 3 7 5 ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 31

Question 1 (Breaking down to small steps) (2) 2 6 4 a(1, 1) 2 + a(1, 2) 2 + a(1, 3) 2 a(2, 1) 2 + a(2, 2) 2 + a(2, 3) 2 a(3, 1) 2 + a(3, 2) 2 + a(3, 3) 2. 3 7 5 2 6 4 Final outcome: p a(1, 1)2 + a(1, 2) 2 + a(1, 3) 2 1 p a(2, 1)2 + a(2, 2) 2 + a(2, 3) 2 1 p a(3, 1)2 + a(3, 2) 2 + a(3, 3) 2 1. 3 7 5 2 6 4 p a(1, 1)2 + a(1, 2) 2 + a(1, 3) 2 p a(2, 1)2 + a(2, 2) 2 + a(2, 3) 2 p a(3, 1)2 + a(3, 2) 2 + a(3, 3) 2. 3 7 5 ENGG1811 UNSW, CRICOS Provider No: 00098G W9 slide 32