The Colon Operator
The colon, :, is one of MATLAB’s most important operators. It occurs in several different
forms. The expression
1 | 1:10 |
is a row vector containing the integers from 1 to 10
1 | 1 2 3 4 5 6 7 8 9 10 |
To obtain nonunit spacing, specify an increment. For example,
1 | 100:-7:50 |
is
1 | 100 93 86 79 72 65 58 51 |
and
is
1 | 0 0.7854 1.5708 2.3562 3.1416 |
Subscript expressions involving colons refer to portions of a matrix.
1 | A(1:k,j.html">j) |
is the first k elements of the jth column of A. So
1 | sum(A(1:4,4)) |
computes the sum of the fourth column. But there is a better way. The colon by itself
refers to all the elements in a row or column of a matrix and the keyword end refers to
the last row or column. So
1 | sum(A(:,end)) |
computes the sum of the elements in the last column of A.
1 2 | ans = 34 |
Why is the magic sum for a 4-by-4 square equal to 34? If the integers from 1 to 16 are
sorted into four groups with equal sums, that sum must be
1 | sum(1:16)/4 |
which, of course, is
1 2 | ans = 34 |
Leave a Reply
You must be logged in to post a comment.