Skip to main content

5.8) Array Indexing (cont'd)


The colon operator can be used to access a sequence of array elements. For example, to access the first column of array "d", we can use:

[matlab]
>> d=[1 2 3 ; 4 5 6 ; 7 8 9];
>> d(1:3,1)
[/matlab]

This will give a column vector "ans" with dimensions 3x1.

[matlab]
ans = 1
4
7
[/matlab]

To access the first row, we can use:

[matlab]
>> d(1,:)
[/matlab]

where the colon (:) can be read as 'the entire row'. The colon can of course be used to specify values in more than one dimension of an array. For example:

[matlab]
>> d(1:2,1:2)
ans = 1 2
4 5
[/matlab]

Note that this doesn't just give us the elements at (1,1) and (2,2); it gives us every element in row 1 or 2 that is also in column 1 or 2.

Again, you can specify the stride. For example, to access all the elements with all odd indices, you can do the following:

[matlab]
>> d(1:2:3, 1:2:3)
>> d([1 3], [1 3])
[/matlab]