Programming 
For the 4by4 matrix A
shown below, it is possible to compute the sum of the elements in the fourth column of A
by typing
You can reduce the size of this expression using the colon operator. Subscript expressions involving colons refer to portions of a matrix. The expression
refers to the elements in rows 1
through m
of column n
of matrix A
. Using this notation, you can compute the sum of the fourth column of A
more succinctly:
Nonconsecutive Elements
To refer to nonconsecutive elements in a matrix, use the colon operator with a step value. The m:3:n
in this expression means to make the assignment to every third element in the matrix. Note that this example uses linear indexing:
The end Keyword
MATLAB provides a keyword called end
that designates the last element in the dimension in which it appears. This keyword can be useful in instances where your program doesn't know how many rows or columns there are in a matrix. You can replace the expression in the previous example with
Note
The keyword end has two meanings in MATLAB. It can be used as explained above, or to terminate a certain block of code (e.g., if and for blocks).

Specifying All Elements of a Row or Column
The colon by itself refers to all the elements in a row or column of a matrix. Using the following syntax, you can compute the sum of all elements in the second column of a 4by4 magic square A
:
By using the colon with linear indexing, you can refer to all elements in the entire matrix. This example displays all the elements of matrix A
, returning them in a columnwise order:
Using a Matrix As an Index
You can repeatedly access an array element using the ones
function. To create a new 2by6 matrix out of the ninth element of a 4by4 magic square A
,
Functions That Control Indexing Style  Logical Indexing 
© 19942005 The MathWorks, Inc.