ABSTRACT

Here is the counterpart of the one-dimensional indexing exercise from Section 5.6. It adds 99 to each entry of the matrix that is larger than .5, using two for loops instead of a single find. This method is slower:

A = rand(3) [m n] = size(A) ; for j = 1:n for i = 1:m if (A(i,j) > .5) A(i,j) = A(i,j) + 99 ; end end end A

The for statement permits any matrix expression to be used instead of 1:n. The index variable consecutively assumes the value of each column of the expression. For example,

s = 0 ; for c = H s = s + sum(c) ; end

computes the sum of all entries of the matrix H by adding its column sums (of course, sum(sum(H)) does it more efficiently; see Section 5.3). Each iteration of the for loop assigns a successive column of H to the variable c. In fact, since 1:n = [1 2 3 ... n], this column-bycolumn assignment is what occurs with for i = 1:n.