Learn R Programming

Matrix (version 1.2-1)

solve-methods: Methods in Package Matrix for Function solve()

Description

Methods for function solve to solve a linear system of equations, or equivalently, solve for $X$ in $$A X = B$$ where $A$ is a square matrix, and $X$, $B$ are matrices or vectors (which are treated as 1-column matrices), and the Rsyntax is X <- solve(A,B) In solve(a,b) in the Matrix package, a may also be a MatrixFactorization instead of directly a matrix.

Usage

## S3 method for class 'CHMfactor,ddenseMatrix':
solve(a, b,
      system = c("A", "LDLt", "LD", "DLt", "L", "Lt", "D", "P", "Pt"), ...)

## S3 method for class 'dgCMatrix,matrix': solve(a, b, sparse = FALSE, tol = .Machine$double.eps, \dots)

solve(a, b, ...) ## *the* two-argument version, almost always preferred to # solve(a) ## the *rarely* needed one-argument version

Arguments

a
a square numeric matrix, $A$, typically of one of the classes in Matrix. Logical matrices are coerced to corresponding numeric ones.
b
numeric vector or matrix (dense or sparse) as RHS of the linear system $Ax = b$.
system
only if a is a CHMfactor: character string indicating the kind of linear system to be solved, see below. Note that the default, "A", does not solve the triangular syst
sparse
only when a is a sparseMatrix, i.e., typically a dgCMatrix: logical specifying if the result should be a (formally) sparse matrix.
tol
only used when a is sparse, in the isSymmetric(a, tol=*) test, where that applies.
...
potentially further arguments to the methods.

See Also

solve, lu, and class documentations CHMfactor, sparseLU, and MatrixFactorization.

Examples

Run this code
## A close to symmetric example with "quite sparse" inverse:
n1 <- 7; n2 <- 3
dd <- data.frame(a = gl(n1,n2), b = gl(n2,1,n1*n2))# balanced 2-way
X <- sparse.model.matrix(~ -1+ a + b, dd)# no intercept --> even sparser
XXt <- tcrossprod(X)
diag(XXt) <- rep(c(0,0,1,0), length.out = nrow(XXt))

n <- nrow(ZZ <- kronecker(XXt, Diagonal(x=c(4,1))))
image(a <- 2*Diagonal(n) + ZZ %*% Diagonal(x=c(10, rep(1, n-1))))
isSymmetric(a) # FALSE
image(drop0(skewpart(a)))
image(ia0 <- solve(a)) # checker board, dense [but really, a is singular!]
try(solve(a, sparse=TRUE))##-> error [ TODO: assertError ]
ia. <- solve(a, sparse=TRUE, tol = 1e-19)##-> *no* error
if(R.version$arch == "x86_64")
  ## Fails on 32-bit [Fedora 19, R 3.0.2] from Matrix 1.1-0 on [FIXME ??] only
  stopifnot(all.equal(as.matrix(ia.), as.matrix(ia0)))
a <- a + Diagonal(n)
iad <- solve(a)
ias <- solve(a, sparse=TRUE)
stopifnot(all.equal(as(ias,"denseMatrix"), iad, tolerance=1e-14))
I. <- iad %*% a          ; image(I.)
I0 <- drop0(zapsmall(I.)); image(I0)
.I <- a %*% iad
.I0 <- drop0(zapsmall(.I))
stopifnot( all.equal(as(I0, "diagonalMatrix"), Diagonal(n)),
           all.equal(as(.I0,"diagonalMatrix"), Diagonal(n)) )

Run the code above in your browser using DataLab