next up previous contents
Next: Graphics Up: Flow Previous: Control

Selective Indexing

The syntax tex2html_wrap_inline2653 to examine or change a specific element of matrix M has already been explained (gif Building Matrices). This can be generalized by replacing row and/or column with vectors of the same height and/or width (respectively) as M with entries all 1 (True) or 0 (False). This specifies a matrix with entries corresponding to those in M whose indices are specified as True in the vectors.

.1ex>> x = [1 2 3 4 5];
.1ex>> x([1 0 1 0 1])
ans =

.1ex>> m = [1 2 3; 4 5 6; 7 8 9];
.1ex>> m([1 0 1], [1 1 0])
ans =


.1ex>> m(3, [1 0 1])
ans =
One rarely enters the indexing vectors by hand this way. Since a relation operator applied to a matrix results in a matrix of 1s and 0s, it is naturally useful to index a matrix of the same size.

.1ex>> x = 3:7
x =

.1ex>> big = x > 4
big =

.1ex>> x(big)
ans =

.1ex>> x(x > 3 & x < 6)
ans =
This is even more useful when specifying elements, or specifying changes to elements, rather than merely viewing them.

.1ex>> disp(x)

.1ex>> x(x > 4) = x(x > 4) + 10
x =

.1ex>> x = 1:5;
.1ex>> x(x > 2) = x(x < 4) + 10
x =

.1ex>> x = 1:5; y = x.2
y =

.1ex>> x(y > 8) = x(y > 8) + y(y > 8)
x =
Let us examine the second example in more detail. We make x [1 2 3 4 5]. The relation tex2html_wrap_inline2717 is then the vector [0 0 1 1 1]; therefore x(x > 2) is the last three elements of x, which currently hold [3 4 5]. On the other side, x < 4 is [1 1 1 0 0], so x(x < 4) is the first three elements of x, which currently hold [1 2 3]. To this matrix is added the scalar 10; adding a scalar to a matrix is always elementwise, so the right-hand side becomes [11 12 13]. Since this is a 1x3 vector and the left-hand side is also a 1x3 vector, the assignment is valid, and the left-hand side (i.e. the last three elements of x) becomes [11 12 13]. MATLAB then prints the entirety of the vector x, including the parts that have not changed: [1 2 11 12 13].

The first and third examples, x(x > 2) = x(x > 2) + 10 and x(y > 8) = x(y > 8) + y(y > 8), are perhaps less general but more typical. They could each be replaced with a for loop over the vectors with an if to perform the test. The selective indexing method is much, much faster, because MATLAB is specifically built to do this sort of thing. The code is also more readable. Therefore, you should use MATLAB in this form whenever possible. Between selective indexing and the colon operator, most procedures can be ``vectorized.''


next up previous contents
Next: Graphics Up: Flow Previous: Control

sepherke
Sat Mar 21 21:42:28 EST 1998