Programming Previous page   Next Page

Accessing Multiple Elements

For the 4-by-4 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

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 4-by-4 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 column-wise order:

Using a Matrix As an Index

You can repeatedly access an array element using the ones function. To create a new 2-by-6 matrix out of the ninth element of a 4-by-4 magic square A,


Previous page  Functions That Control Indexing Style Logical Indexing Next page

© 1994-2005 The MathWorks, Inc.