• Matlab TutorialsNo Comments

    default thumbnail

    The colon, :, is one of ’s most important operators. It occurs in several different
    forms. The expression

    1:10

    is a row containing the integers from 1 to 10

    1     2     3     4     5     6     7     8     9    10

    To obtain nonunit spacing, specify an increment. For ,

    100:-7:50

    is

    100    93    86    79    72    65    58    51

    and

    0:pi/4:pi

    is

    0    0.7854    1.5708    2.3562    3.1416

    Subscript expressions involving colons refer to portions of a .

    A(1:k,j)

    is the first k elements of the jth column of A. So

    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 refers to
    the last row or column. So

    sum(A(:,end))

    computes the sum of the elements in the last column of A.

    ans =
         34

    Why is the magic sum for a 4-by-4 square equal to 34? the integers from 1 to 16 are
    sorted into four groups with equal sums, that sum must be

    sum(1:16)/4

    which, of course, is

    ans =
         34
    You might also be interested in :  elseif

    Comment closed!