VectorMatrixAddon {fUtilities}R Documentation

Vector/Matrix Arithmetics and Linear Algebra

Description

A collection and description of functions available for matrix arithmetics and linear algebra.

Only functions which have been added by Rmetrics are documented. These functions are often useful for the manipulation of multivariate time series.

The origin of the functions is marked in the following way:

R: part of R's base packages,
B: part of Rmetrics' fBasics package,
M: part of this Rmetrics package, fMultivar.

The functions are listed by topic.

General Matrix Functions:

matrix Creates a matrix from the given set of values,
diag Creates a diagonal matrix or extracts diagonals,
triang Extracs the lower tridiagonal part from a matrix,
Triang Extracs the upper tridiagonal part from a matrix,
pascal Creates a Pascal matrix,
hilbert Creates a Hilbert matrix,
colVec Creates a column vector from a vector,
rowVec Creates a row vector from a vector,
as.matrix Attempts to turn its argument into a matrix,
is.matrix Tests if its argument is a (strict) matrix,
isPositiveDefinite Checks if a matrix is positive definite,
makePositiveDefinite Forces a matrix to be positive definite,
dimnames Retrieves or sets the dimnames of an object,
colnames Retrieves or sets the column names,
colIds ... use alternatively,
rownames Retrieves or sets the row names,
rowIds ... use alternatively.

Simple Matrix Operations:

dim Returns the dimension of a matrix object,
ncol Counts columns of a matrix object,
nrow Counts rows of a matrix object,
length Counts elements of a matrix object,
"[" Subsets a matrix object,
"[[" Subsets a matrix object,
cbind Augments a matrix object by columns,
rbind Augments a matrix object by rows.

Basic Statistical Functions:

var Returns the variance matrix,
cov Returns the covariance matrix,
colStats Calculates column statistics,
rowStats Calculates row statistics,
colMeans Calculates column means,
rowMeans Calculates row means,
colAvgs Calculates column averages,
rowAvgs Calculates row averages,
colVars Calculates column variances,
rowVars Calculates row variances,
colStdevs Calculates column standard deviations,
rowStdevs Calculates row standard deviations,
colSkewness Calculates column skewness,
rowSkewness Calculates row skewness,
colKurtosis Calculates column kurtosis,
rowKurtosis Calculates row kurtosis,
colCumsums Calculates column cumulated sums,
rowCumsums Calculates row cumulated sums.

Linear algebra:

%*% Returns the product of two matrices,
%x%, kron Returns the Kronecker product,
det Returns the determinante of a matrix,
inv Returns the inverse of a matrix,
norm Returns the norm of a matrix,
rk Returns the rank of a matrix,
tr Returns trace of a matrix,
t Returns the transposed matrix,
vech Is the operator that stacks the lower triangle,
vec Is the operator that stacks a matrix.

More linear algebra:

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

Time Series Generation:

tslag Lagged or leading vector/matrix of selected order(s),
pdl Regressor matrix for polynomial distributed lags.

Usage

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

isPositiveDefinite(x)
makePositiveDefinite(x)

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

isPositiveDefinite(x)
makePositiveDefinite(x)

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

vec(x)
vech(x)

pdl(x, d = 2, q = 3, trim = FALSE)
tslag(x, k = 1, trim = FALSE)

Arguments

d [pdl] -
an integer specifying the order of the polynomial.
k [tslag] -
an integer value, the number of positions the new series is to lag or to lead the input series.
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.
q [pdl] -
an integer specifying the number of lags to use in creating polynomial distributed lags. This must be greater than d.
trim [pdl] -
a logical flag; if TRUE, the missing values at the beginning of the returned matrix will be trimmed.
[tslag] -
a logical flag, if TRUE, the missing values at the beginning or end of the returned series will be trimmed. The default value is FALSE.
x, y a numeric matrix.
[tslag] -
a numeric vector, missing values are allowed.
[pdl] -
a numeric vector.
... 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 function hilbert generates a Hilbert matrix of order n.

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 function isPositiveDefinite checks if a square matrix is positive definite, and the function makePositiveDefinite forces a matrix to be positive definite.

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 vec implements the operator that stacks a matrix as a column vector, to be more precise in a matrix with one column. vec(X) = (X11, X21, ..., XN1, X12, X22, ..., XNN). The function vech implements the operator that stacks the lower triangle of a NxN matrix as an N(N+1)/2x1 vector: vech(X) =(X11, X21, X22, X31, ..., XNN), to be more precise in a matrix with one row.

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.

Time Series:
The function pdl returns a regressor matrix suitable for polynomial distributed lags.
The function tslag returns a lagged/led vector or matrix for given time series data.

Author(s)

Diethelm Wuertz for the Rmetrics 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.

Ward, R.C., (1977); Numerical computation of the matrix exponential with accuracy estimate, SIAM J. Num. Anal. 14, 600–610.

Moler C., van Loan C., (2003); Nineteen dubious ways to compute the exponential of a matrix, twenty-five years later, SIAM Review 45, 3–49.

Examples

## Create Pascal Matrix:
   P = pascal(3)
   P
   # Create lower triangle matrix
   L = triang(P)
   L
   # Extract diagonal part
   diag(P)
   
## Add/Subtract/Multiply/Divide:  
   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:
   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: 
   # 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:
   # 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) 
   # Stack a matrix
   vec(P) 
   # Stack the lower triangle
   vech(P)
   
## More 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 fUtilities version 260.72 Index]