Both vectors and matrices are created using a pair of square brackets, []. Each element is separated by a comma. A vector is a matrix with one of the dimensions equal to 1.
Here is an example of creating a vector (1-dimensional matrix):
> x = [1,2,3]; print(x)
[Matrix] (1 x 3)
1 2 3
The above example creates a row vector with dimensions of 1 row by 3 columns (1x3). To make a 3x1 vector, separate the entries by a semicolon (;).
> x = [1;2;3]; print(x)
[Matrix] (3 x 1)
1
2
3
Matrices are limited to 2 dimensions. A matrix is created by extending the above concept. Here is a 2x3 matrix:
> x = [1, 2, 3; 4, 5, 6]; print(x)
[Matrix] (2 x 3)
1 2 3
4 5 6
Each row must have the same number of columns.
A range can also be specified using the format begin:inc:end, which starts with the number begin and change in increments of inc until it reaches end. If the increment causes the last element to be greater than end, then it ends at the previous item. The increment is optional and defaults to 1.
> x = [1:5]; print(x)
[Matrix] (1 x 5)
1 2 3 4 5
> x = [1:2:5]; print(x) // increment by 2
[Matrix] (1 x 3)
1 3 5
> x = [1:2:6]; print(x) // will produce the same result since 6 is skipped over
[Matrix] (1 x 3)
1 | 3 5 |
> x = [5:-1:1]; print(x) // in reverse
[Matrix] (1 x 5)
5 | 4 3 2 1 |
> x = [1, 10:5:20]; print(x) // can be of mixed form
[Matrix] (1 x 4)
1 | 10 15 20 |
This format can be used for creating matrices as well.
> x = [1:3; 4, 5, 6]; print(x)
[Matrix] (2 x 3)
1 2 3
4 5 6
An empty matrix can also be created.
> x=[]; print(x)
[Matrix] 0 x 0
Note | The maximum number of elements in a vector/matrix is limited to 2147483646. |