matrixAddon {fSeries}R Documentation

Matrix Arithmetics and Linear Algebra

Description

This help page summarizes selected functions available under R for matrix arithmetics and linear algebra. Addititionally functions are documented which have been added by Rmetrics.

The origin of the functions is marked in the following way: R: part of R's base packages, B: part of Rmetrics' fBasics package, S: part of this Rmetrics package, fSeries.

The functions are listed by topic.

General Matrix Functions:

1

matrix Creates a matrix from the given set of values,
2 diag R: Creates a diagonal matrix or extracts diagonals,
3 triang S: Extracs the lower tridiagonal part from a matrix,
4 Triang S: Extracs the upper tridiagonal part from a matrix,
5 pascal S: Creates a Pascal matrix,
6 colVec S: Creates a column vector from a vector,
7 rowVec S: Creates a row vector from a vector,
8 as.matrix R: Attempts to turn its argument into a matrix,
9 is.matrix R: Tests if its argument is a (strict) matrix,
10 dimnames R: Retrieves or sets the dimnames of an object,
11 colnames, rownames R: Retrieves or sets the row or column names,
12 colIds, rowIds R: ... use alternatively,

Simple Matrix Operations:

1

dim R: Returns the dimension of a matrix object,
2 ncol, nrow R: Counts columns|rows of a matrix object,
3 length R: Counts elements of a matrix object,
4 "[", "[[" R: Subsets a matrix object,
5 cbind, rbind R: Augments a matrix object by columns|rows,

Basic Statistical Functions:

1

var R: Returns the variance matrix,
2 cov R: Returns the covariance matrix,
3 colStats, rowStats B: Calculates column|row statistics,
4 colMeans, rowMeans B: Calculates column|row means,
5 colAvgs, rowAvgs B: Calculates column|row averages,
6 colVars, rowVars B: Calculates column|row variances,
7 colStdevs, rowStdevs B: Calculates column|row standard deviations,
8 colSkewness, rowSkewness B: Calculates column|row skewness,
9 colKurtosis, rowKurtosis B: Calculates column|row kurtosis,
10 colCumsums, rowCumsums B: Calculates column|row cumulated sums,

Linear Algebra:

1

%*% R: Returns the product of two matrices,
2 %x%, kron R: Returns the Kronecker product,
3 det R: Returns the determinante of a matrix,
4 inv S: Returns the inverse of a matrix,
5 norm S: Returns the norm of a matrix,
6 rk S: Returns the rank of a matrix,
7 tr S: Returns trace of a matrix,
8 t R: Returns the transposed matrix,

More Linear Algebra:

1

chol R: Returns the Cholesky factor matrix,
2 eigen R: Returns eigenvalues and eigenvectors,
3 svd R: Returns the singular value decomposition,
4 kappa R: Returns the condition number of a matrix,
5 qr R: Returns the QR decomposition of a matrix,
6 solve R: Solves a system of linear equations,
7 backsolve R: ... use when the matrix is upper triangular,
8 forwardsolve R: ... use when the matrix is lower triangular.

Usage

triang(x)
Triang(x)
pascal(n)

colVec(x)
rowVec(x)
colIds(x, ...)
rowIds(x, ...)

inv(x)
norm(x, p = 2)
rk(x, method = c("qr", "chol"))
tr(x)
kron(x, y)

Arguments

method [rk] -
a character value, the dimension of the square matrix. One can choose from two methods: For method = "qr" the rank is computed as qr(x)$rank, or alternatively for method = "chol" the rank is computed as attr(chol(x, pivot = TRUE), "rank").
n [pascal] -
an integer value, the dimension of the square matrix
p [norm] -
an integer value, 1, 2 or Inf. p=1 - The maximum absolute column sum norm which is defined as the maximum of the sum of the absolute valued elements of columns of the matrix. p=2 - The spectral norm is "the norm" of a matrix X. This value is computed as the square root of the maximum eigenvalue of CX where C is the conjugate transpose. p=Inf - The maximum absolute row sum norm is defined as the maximum of the sum of the absolute valued elements of rows of the matrix.
x, y a numeric matrix.
... arguments to be passed.

Details

Function from R's Base Package:

Most of the functions are described in their R help pages which we recommend to consult for further information. For the additiotnal functions added by Rmetrics we give a brief introduction.

General Functions:

Functions to generate matrices and related functions are described in the help page matrix. To "decorate" these objects several naming functions are available, a description can be found on the help pages dimnames and rownames.

The function pascal generates a Pascal matrix of order n which is a symmetric, positive, definite matrix with integer entries made up from Pascal's triangle. The determinant of a Pascal matrix is 1. The inverse of a Pascal matrix has integer entries. If lambda is an eigenvalue of a Pascal matrix, then 1/lambda is also an eigenvalue of the matrix. Pascal matrices are ill-conditioned.

The functions triang and Triang allow to transform a square matrix to a lower or upper triangular form. A triangular matrix is either an upper triangular matrix or lower triangular matrix. For the first case all matrix elements a[i,j] of matrix A are zero for i>j, whereas in the second case we have just the opposite situation. A lower triangular matrix is sometimes also called left triangular. In fact, triangular matrices are so useful that much computational linear algebra begins with factoring or decomposing a general matrix or matrices into triangular form. Some matrix factorization methods are the Cholesky factorization and the LU-factorization. Even including the factorization step, enough later operations are typically avoided to yield an overall time savings. Triangular matrices have the following properties: the inverse of a triangular matrix is a triangular matrix, the product of two triangular matrices is a triangular matrix, the determinant of a triangular matrix is the product of the diagonal elements, the eigenvalues of a triangular matrix are the diagonal elements.

The functions colVec and rowVec transform a vector into a column and row vector, respectively. A column vector is a matrix object with one column, and a row vector is a matrix object with one row.

The functions dimnames, colname, and rowname can be used to retrieve and set the names of matrices. The functions rowIds, colIds, are S-Plus like synonyms.

Simple Matrix Operations:

The functions dim, nrow and ncol are functions to extract the dimension and the number of rows and columns of a matrix.

The usual arithmetic operators, logical operators and mathematical functions like sqrt or exp and log operate on matrices element by element. Note, that "*" is not matrix multiplication, instead we have to use "%*%".

The methods "[" and "[[" are suited to extract subsets from a matrix, to delete rows and columns, or to permute rows and columns.

Basic Statistical Functions:

The functions var and cov compute the variance and covariance of a matrix.

Beside these functions colMeans and rowMeans are R functions which compute the mean of columns and rows of a matrix. Rmetrics has added further functions to compute column- or rowwise variances, standard deviations, skewness, kurtosis and cumulated sums. Two general functions named rowStats and colStats allow to apply through the argument list any function to compute row and column statistics from matrices.

Linear Algebra:

Matrix multiplication is done using the operator %*%.

The Kronecker product can be computed using the operator %x% or alternatively using the function kron.

The function det computes the determinant of a matrix.

The inverse of a square matrix inv(X) of dimension n is defined so that X %*% inv(X) = inv(X) %*% X = diag(n) where the matrix diag(n) is the n-dimensional identity matrix. A precondition for the existence of the matrix inverse is that the determinant of the matrix det(X) is nonzero.

The function t computes the transposed of a square matrix.

The function tr computes the trace of a square matrix which is the sum of the diagonal elements of the matrix under consideration.

The function rk computes the rank of a matrix which is the dimension of the range of the matrix corresponding to the number of linearly independent rows or columns of the matrix, or to the number of nonzero singular values. The rank of a matrix is also named inear map.

The function norm computes the norm of a matrix. Three choices are possible: p=1 - The maximum absolute column sum norm which is defined as the maximum of the sum of the absolute valued elements of columns of the matrix. p=2 - The spectral norm is "the norm" of a matrix X. This value is computed as the square root of the maximum eigenvalue of CX where C is the conjugate transpose. p=Inf - The maximum absolute row sum norm is defined as the maximum of the sum of the absolute valued elements of rows of the matrix.

More Linear Algebra:

The function chol returns the Cholesky factor matrix, eigen returns eigenvalues and eigenvectors, svd returns the singular value decomposition, kappa estimate the condition number of a matrix, qr returns the QR decomposition of a matrix, ginv returns the Moore-Penrose generalized inverse, solve solves a system of linear equations, use backsolve when the matrix is upper triangular, and forwardsolve when the matrix is lower triangular.

Author(s)

Diethelm Wuertz for the addons of this R-port.

References

Higham N.J., (2002); Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM.

Golub, van Loan, (1996); Matrix Computations, 3rd edition. Johns Hopkins University Press.

Examples

## Examples:

## Create Pascal Matrix:
   xmpSeries("\nStart: Pascal Matrix > ")
   P = pascal(3)
   P
   # Create lower triangle matrix
   L = triang(P)
   L
   # Extract diagonal part
   diag(P)
   
## Add/Subtract/Multiply/Divide:  
   xmpSeries("\nNext: Math Operations > ")
   X = P
   # Multiply matrix with a constant
   3 * X
   # Multiply two matrices elementwise
   X * P                     
   # Multiplies rows/columns of a matrix by a vector
   X %*% diag(P)            
   diag(P) %*% X           
       
## Operate on Subsets of a Matrix:
   xmpSeries("\nNext: Matrix Subsets > ")
   n = 3; i = 2; j = 3
   D = diag(1:3)
   # Return the dimension of a matrix
   dim(P)                         
   # Get the last colum of a matrix
   P[, ncol(P)]                   
   # Delete a column of a matrix
   P[, -i]                      
   # Permute the columns of a matrix
   P[c(3, 1, 2), ]              
   # Augments matrix horizontally 
   cbind(P, D)                           
      
## Apply a function to all Elements of a Matrix: 
   xmpSeries("\nNext: Operate Element by Element > ")
   # Return square root for each element
   sqrt(P)
   # Exponentiate the matrix elementwise
   exp(P)
   # Compute the median of each column
   apply(P, 2, "median") 
   # Test on all elements of a matrix       
   all( P > 2 )   
   # test on any element in a matrix                
   any( P > 2 )                  
     
## More Matrix Operations:
   xmpSeries("\nNext: More Matrix Operations > ")
   # Return the product of two matrices
   P %*% D   
   # Return the Kronecker Product                     
   P %x% D                        
   # Return the transposed matrix
   t(P)                           
   # Return the inverse of a matrix
   inv(P)  
   # Return the norm of a matrix                      
   norm(P)                        
   # Return the determinante of a matrix
   det(P)                         
   # Return the rank of a matrix
   rk(P)                            
   # Return trace of a matrix
   tr(P)                          
   # Return the variance matrix
   var(P)     
   # Return the covariance matrix                   
   cov(P)                         
    
## More Linear Algebra:
   xmpSeries("\nNext: Linear Algebra > ")
   X = P; b = c(1, 2, 3)
   # Return the Cholesky factor matrix
   chol(X)                        
   # Return eigenvalues and eigenvectors
   eigen(X)                       
   # Return the singular value decomposition
   svd(X)                         
   # Return the condition number of a matrix
   kappa(X)                       
   # Return the QR decomposition of a matrix
   qr(X)                          
   # Solve a system of linear equations
   # ... use backsolve when the matrix is upper triangular
   # ... use forwardsolve when the matrix is lower triangular
   solve(X, b)  
   backsolve(Triang(X), b)
   solve(Triang(X), b)                 
   forwardsolve(triang(X), b) 
   solve(triang(X), b)                                        

[Package Contents]