HyperMath

Indexing Multiple Elements

Indexing Multiple Elements

Previous topic Next topic No expanding text in this topic  

Indexing Multiple Elements

Previous topic Next topic JavaScript is required for expanding text JavaScript is required for the print function  

Multiple indexing is done by including a pair of square brackets inside a pair of parenthesis, ([]).  The result is a vector or matrix.

> x = [1, 2, 3, 4];

> print(x([2,4])) // get second & fourth item as an array

[Matrix] 1 x 2

2      4

For a matrix, the above is accessed using linear indexing.

A range of elements can also be accessed using the colon (:) operator.

> x = [1, 2, 3, 4];

> print(x([2:4])) // get 2nd through 4th items as an array

[Matrix] (1 x 3)

2        3        4

For a matrix, this can be used to extract specific items, such as specific rows or columns.

> x = [1, 2, 3; 4, 5, 6; 7, 8, 9]; print(x)

[Matrix] (3 x 3)

1        2        3

4        5        6

7        8        9

> print(x([1,3],2)) // get 2nd column in rows 1 & 3, as a column vector

[Matrix] (2 x 1)

2

8

> print(x([1,3],[2,3])) // get 2nd & 3rd column in rows 1 & 3

[Matrix] (2 x 2)

2        3

8        9

> print(x([1,3],[1:3])) // get columns 1 to 3 in rows 1 & 3

[Matrix] (2 x 3)

1        2        3

7        8        9

A colon (:) can be used to denote all items in a given dimension.

> print(x([1,3],:)) // get all columns in rows 1 & 3

[Matrix] (2 x 3)

1        2        3

7        8        9

Entire rows or columns can be removed by making them empty.

> x([1,3],:) = []; print(x); // removes rows 1 & 3

[Matrix] 1 x 3

4    5     6