Presentation is loading. Please wait.

Presentation is loading. Please wait.

MATLAB Programming Indexing Copyright © Software Carpentry 2011

Similar presentations


Presentation on theme: "MATLAB Programming Indexing Copyright © Software Carpentry 2011"— Presentation transcript:

1 MATLAB Programming Indexing Copyright © Software Carpentry 2011
Hello, and welcome to another episode of the Software Carpentry lecture on MATLAB. In this episode, we'll have a look at some of the ways you can index arrays. As we'll see, clever indexing allows you to avoid writing loops, which both reduces the size of your code, and makes your code more efficient. Copyright © Software Carpentry 2011 This work is licensed under the Creative Commons Attribution License See for more information. 1

2 Can access individual elements >>> block 10 20 30 40
>>> block(1, 2) 20 2 10 20 30 40 110 120 130 140 210 220 230 240 Individual elements in an array can be accessed using a comma separated list of integer indices. 1

3 Can access individual elements >>> block 10 20 30 40
>>> block(1, 2) 20 2 10 20 30 40 110 120 130 140 210 220 230 240 In most programming languages, the first element of an array is element 0. In MATLAB, indexes start at 1. 1 1 – based index.

4 Can slice arrays with another list. >>> 1:3 ans 1 2 3
>>> block(1:3, 1:2) 1:2 10 20 30 40 110 120 130 140 210 220 230 240 Arrays can be sliced by using another array as an index. In this example, we use the array 1, 2, 3, which we can create using the shorthand 1 colon 3 notation. 1:3

5 Easier for later programmers to understand… Runs faster…
Why use a slice? No loops! Shorter… Easier for later programmers to understand… Runs faster… MATLAB programs should always use slices and other indexing operations rather than write loops over arrays. There are several advantages, including shorter code that is more easily understood, and improved runtime. 5

6 >>> block(2, 2:3) = 0 >>> block 10, 20, 30, 40
Can assign to slices >>> block(2, 2:3) = 0 >>> block 10, 20, 30, 40 110, 0, 0, 140 210, 220, 230, 240 It is also possible to assign to slices. For example, we can assign zero to columns 2 and 3 in row 2 of 'block' in a single statement.

7 Assigning a slice makes a copy:
>>> smallBlock = block(1:3, 1:2); >>> smallBlock(1,1) = 15; >>> block(1,1) 10 >>> smallBlock(1,1) 15 1:2 15 20 110 120 210 220 An array slice makes a copy of the underlying array, which means that the data values are copied to a new location and subsequent updates do not change the original matrix. 10 20 30 40 110 120 130 140 210 220 230 240 1:3 smallBlock block 7

8 Slice on both sides to shift data
>>> vector = [10, 20, 30, 40]; >>> vector(1:3) = vector(2:4); >>> vector [20, 30, 40, 40] Not overwritten Slicing on both sides gives us a way to shift data along the axes. If 'vector' is a one-dimensional array as shown here, then 'vector[1:3]' selects slots 1, 2, and 3… …while 'vector[2:4]' selects the values in slots 2, 3, and 4. Doing the assignment overwrites the lower three values, but it leaves the uppermost untouched). 8

9 Slice on both sides to shift data
>>> vector = [10, 20, 30, 40]; >>> vector(1:3) = vector(2:4); >>> vector [20, 30, 40, 40] Investigate circshift(vector, 1) which is a MATLAB function that does something similar. Not overwritten MATLAB has a function circshift, which shifts values in an array in a circular pattern. Rather than discard the leftmost item, it is placed in the rightmost spot and all other values are shifted left. 9

10 Can use lists or arrays as subscripts >>> vector
[0, 10, 20, 30] >>> subscript = [4, 2, 3] >>> vector( subscript ) [30, 10, 20] vector subscript result To perform more sophisticated indexing operations, we can use an array as a set of subscripts. For example, here's our four-element vector again… …and a list with three legal subscripts: 4, 2, and 3. The expression 'vector[subscript]' creates a new array, whose elements are selected from 'vector' as you'd expect. 10 20 30 4 2 3 30 10 20

11 >>> vector < 25 [ 1 1 1 0] What type is the answer?
Comparisons >>> vector [0, 10, 20, 30] >>> vector < 25 [ ] What type is the answer? Masks: >>> vector(vector < 25) [ ] Arrays can also be used in comparisons… When we use the result of a comparison in an index, we only get those values that satisfy the condition. Almost all arrays in MATLAB are of type double, which means they are floating point numbers. When a matrix is used in a comparison, the result is not a double: it is a matrix of integer 0s and 1s.

12 Comparisons are arrays of booleans.
Most MATLAB arrays are made of double precision floating point numbers. Comparisons are arrays of booleans. MATLAB displays booleans as either 1 or 0. >>> v = [ ]; >>> m = v < 4 [ ] >>> m2 = [ ]; >>> v(m); This is okay. >>> v(m2); This is an error These are booleans that look like doubles. The difference is apparent in this example. Here, the array ‘m’ is the result of a comparison, and we can see that a 1 means that the corresponding element of v was less than 4. The array ‘m2’ is hand constructed with the same pattern as m, but the values are doubles since this is the default. Try to use m and m2 as an index. The result of the comparison can be used but m2 fails because indices must be integers, not doubles. These are doubles.

13 Use a Boolean subscript as a mask >>> vector [0, 10, 20, 30]
>>> vector( vector < 25 ) [0, 10, 20] vector vector < 25 result 10 20 30 1 10 20 Another term for an index from a comparison is a mask, because the boolean array masks all of the elements of vector that fail the condition.

14 Use masking for assignment
>>> mask = [true, false, true, false]; >>> a(mask) = [100, 101]; >>> a [100, 1, 101, 3] result mask mask fill a We can use Boolean masking on the left side of assignment as well, though we have to be careful about its meaning. If we use a mask directly, elements are taken in order from the source on the right and assigned to elements corresponding to True values in the mask. 100 101 100 1 101 3 1 2 3 1 2 3 1 Taken in order

15 Use the mask on both sides to selectively combine two arrays:
>>> mask = [true, false, true, false]; >>> fill = [ ]; >>> a(mask) = fill(mask) [100, 1, 102, 3] result a mask fill Using a mask on both sides of an assignment has a different effect. Corresponding elements of the array ‘fill’ are assigned to ‘a’ if the location meets the criteria in mask. In both cases, only locations corresponding to True values in the mask are affected; it's what happens at the source that changes. 100 1 102 3 1 2 3 T F 100 101 102 103 Taken where True

16 When an array is masked, its size changes.
How can we keep the array the same size? >>> v = [ ]; >>> m = v > 1; >>> v(m) [ 2 3] >>> v .* m [ ] Booleans act like 0 and 1 in arithmetic expressions. Sometimes we want to replace values in a matrix with 0s without changing the size of the result. We can use the boolean mask and element-wise multiplication to replace locations that are less than 1 with zeros.

17 Logical operators &, |, and ~ operate element-wise on MATLAB arrays.
MATLAB also defined && and ||, but they operate on scalars only. Use & and | rather than && and || to avoid confusion. ~ is “not”. ~0 is 1 and ~a for anything else is 0. There are two sets of logical operators in MATLAB. A single & or vertical bar corresponds to elementwise “AND” and “OR” on an array. Double AND and double OR operate on scalars only. It is usually preferable to use the single AND or single OR since they work in both cases.

18 Logical operators act on all numerical types: 0 is ‘false’
Everything else is ‘true’ Be careful about relying on logical comparisons to find zeros in floating point numbers: A number that is very small but nonzero is still ‘true’. In logical expressions, zero is the only number that is false. Be careful though: very small numbers are still nonzero even if they look like zero when you print them.

19 – Or subscripted with vectors of indices – Or masked with conditionals
Review: – Arrays can be sliced – Or subscripted with vectors of indices – Or masked with conditionals To review… Arrays can be sliced with vectors of indices… …or masked with conditionals.

20 – Or subscripted with vectors of indices – Or masked with conditionals
Review: – Arrays can be sliced – Or subscripted with vectors of indices – Or masked with conditionals LOOPS No matter what you do, if you are writing loops over array elements, you have probably missed something, or are doing something wrong. 20

21 Richard T. Guy created by February 2011
In our next episode, we'll use the tools we have looked at so far to explore some linear algebra. February 2011 Copyright © Software Carpentry 2011 This work is licensed under the Creative Commons Attribution License See for more information. 21


Download ppt "MATLAB Programming Indexing Copyright © Software Carpentry 2011"

Similar presentations


Ads by Google