Matrices

A matrix is a rectangular array of numbers. it can be created with elements included in a pair of square brackets. The rows are separated by semicolons, while elements in the same row are separated by commas.
>> A = [1,4, 9; 2, 3, 5; -2, 5, 10]
   1   4    9
   2   3    5
  -2   5   10
To refer to the element of matrix A at second row and third column, use A[2,3]
>> A[2,3]
   5

Create Matrices

Alternatively, a matrix of a required size can be created and initialized using built-in functions zeros, ones, or rand. The command

A = zeros(3, 5)
will return a matrix of three rows and five columns, with each element being zero. Similar usage of ones and rand will create matrices of 1's and random numbers (between 0 and 1) respectively.

These three functions can also be called with a single parameter, in which case the second parameter is assumed to be 1, and thus a column vector is created.

>> B = rand(5)
    0.289    
    0.353    
    0.154    
    0.566    
    0.821
By the dimension of a matrix we refer to the number of rows and the number of columns. For example, the dimension of the scalar -5 is $ \texttt{1} \times \texttt{1}$, while the dimension of the matrix
   -2    3    9
    10   1    -2
is $ \texttt{2} \times \texttt{3}$.

Create Even Spaced Vectors Using the Colon Operator

The symbol : can be used to create a row matrix whose elements are evenly spaced. The default step-size of the vector is 1, which is assumed when one colon is used.

>> A = -1 : 5
   -1  0  1  2  3   4   5
To specify a step-size other than 1, two colons are needed.
>> A = 3 : 0.5 : 5
   3  3.5  4  4.5  5
When you use A : B to create a vector, the value B is not always included in the vector. Alternatively, the built-in function linspace can be used to created even spaced vector with the specified end points included. linspacea, b, n will create a column vector of length n, with a and b being the two end points.

oz 2009-12-22