21. Vectorization

# 21. Vectorization - ENGR 101, Section 100, Fall 10...

This preview shows pages 1–6. Sign up to view the full content.

ENGR 101, Section 100, Fall 10 M. Wellman 1 Subarrays and Vectorization ENGR 101, Lecture 21: 29 Nov 10 Announcements Project 7 due Wed 1 Dec Try to get done early, to avoid MATLAB license contention Note on conversion to doubles Watch for Project 8 soon…

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
ENGR 101, Section 100, Fall 10 M. Wellman 2 Accessing Array Elements Parentheses denote index operator ( ) unlike C++, MATLAB indices start at 1 Example: b = [1.0 3.0 5.0 2.0 4.0 6.0 ] b(1,3) 5.0 b(2,2) = 12 b = [1.0 3.0 5.0 2.0 12.0 6.0 ] Vectors as Indices Specifying a vector index selects a subarray with elements corresponding to the indices in the vector If v is a vector with n elts, then x(v) is equivalent to: [x(v(1)), x(v(2)), …, x(v(n))] For example, given: x = [ 1 7 4 –1 13 ] x(3) 4 x([1 3 5]) [1 4 13]
ENGR 101, Section 100, Fall 10 M. Wellman 3 Vectors as Matrix Indices Can also use vector indices on matrices For example, given: x = [ 1 7 4 –1 13 ] M = [ x; x+1; x+2 ] M(1,[1 3 5]) [1 4 13] M([1 2],[1 3 5]) ? [1 4 13 2 5 14] Colon Operator in Indices Colon operator provides shortcut to define vectors, so can use in vector index For example, given: x = [ 1 7 4 –1 13 ] x(2:4) [7 4 -1] Keyword end denotes last element: x(3:end) [4 -1 13] Colon on its own selects all values M = [ x; x+1; x+2 ] M(2,:) [2 8 5 0 14] M(:,[2 4]) [7 -1 8 0 9 1 ]

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
ENGR 101, Section 100, Fall 10 M. Wellman 4 Assigning to Subarrays arr = [ 1:4; 5:8; 9:12 ] arr([1 3],1:2) = [ -4 -3; -2 -1 ] arr(:,[2 4]) = 0 3 5 7 11 -4 -2 0 0 0 0 0 0 Exercise: Which does not generate the matrix shown? -1 -1 0 0 0 0 0 -1 -1 0 0 0 0 0 0 0 3 3 3 0 0 0 0 3 3 3 0 0 0 0 0 0 0 -1 -1 0 0 0 0 0 -1 -1 A B C
ENGR 101, Section 100, Fall 10 M. Wellman 5 What does this Function Do? function vout = myFunc (vin) vout = vin; vout(1:2:end-1) = vin(2:2:end); vout(2:2:end) = vin(1:2:end-1); Iteration and Vectorization Explicit iteration constructs: while for Elt-by-elt operations on arrays can also effectively

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## 21. Vectorization - ENGR 101, Section 100, Fall 10...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online