Matrices



Matrices are created "on demand". If a matrix, or matrix element, appears on the left hand side of an assignment statment then a matrix of sufficient size is created to implement the assignment.

For example,

>>M(5,5) = 3.0; 

assigns the value 3.0 to the (5,5) element of M. If M is not of sufficient size, then M is redimensioned to a 5x5 matrix to accomodate the assignment. .

M(i,j) accesses to the (i,j) element of a matrix M.

Indexing starts at (1,1).

A range of indices can be accessed using the : notation, e.g. M(1:3,4:5) refers to the block submatrix of M consisting of row 1 to 3 and columns 4 to 5.

Element by element operations are implement with the "dot" operators
.+ .- .* ./ .^

Matrix addition, subtraction,multiplication, exponentiation and inversion are implemented with the operators +, - , *, ^, \ and / respectively. The matrix backslash operator, is essentially defined by A\B = A-1*B, while the foreslash operator is defined by A/B = A*B-1.

If two matrices are not compatable sizes for an algebraic operation, then an error message is generated.

In addition to constructing matrix elements by looping over the indices, one can use explicit assignment statements, for example to input a 2x2 matrix one could use

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

Useful matrix commands

M' or transpose(M) Returns the transpose of M.
size(matrixVariable) Returns the row and column dimensions of matrixVariable as a vector
diag(...) The diag command can be used to extracts matrix diagonals, as well as create diagonal matrices.. See Matlab diag for details.
qr Computes the qr factorization of a matrix. See Matlab qr for details.
eig Computes the eigenvalues and eigenvectors of a matrix. See Matlab eig for details.
svd Computes the singular value decomposition of a matrix. See Matlab svd for details.
chol
lu
Routines for creating and working with upper and lower triangular factors of matrices. See Matlab chol and lu for details.
expm, logm 
Computes the matrix exponentional and matrix logarithm. See expm and logm for details.

Samples

% Creating a 5x5 matrix initialized to zero

  m(5,5) = 0.0
  m =
     0     0     0     0     0
     0     0     0     0     0
     0     0     0     0     0
     0     0     0     0     0
     0     0     0     0     0

% Checking the size

  size(m)
  ans =
     5     5

% Setting a matrix value

  m(5,3) = 2.0;
  m
  m =
     0     0     0     0     0
     0     0     0     0     0
     0     0     0     0     0
     0     0     0     0     0
     0     0     2     0     0

% Creating a matrix explictly

  M =[ 0, 1; 20, 2]
  M =
     0     1
    20     2

% Setting up a column vector to be the right hand side of a linear equation

  b = [0 ; 1]
  b =
     0
     1

% Solving the matrix equation M x = b

  M\b
  ans =
    0.0500
         0


UCLA Mathematics Department ©2000