chapter  7
8 Pages

Control Flow Statements

Here is the counterpart of the one-dimensional indexing exercise from pages 29 and 31. It adds 99 to each entry of the matrix that is larger than .5. It is slower than using find or logical indexing.

A = rand(5)

[m n] = size(A) ;

for j = 1:n

for i = 1:m

if (A(i,j) > .5)

A(i,j) = A(i,j) + 99 ;





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) ;


“8primer” — #62

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-by-column assignment is what occurs with for i = 1:n. In most statements, the colon operator creates a list of numbers in a MATLAB array. It works differently in a for loop. The assignment i = 1:inf fails because the list is too big to be created. The statement for i=1:inf does not create the list, and becomes just another way of specifying an infinite loop.