| Version: | 1.7-4 |
| VersionNote: | do also bump src/version.h, inst/include/Matrix/version.h |
| Date: | 2025-08-27 |
| Priority: | recommended |
| Title: | Sparse and Dense Matrix Classes and Methods |
| Description: | A rich hierarchy of sparse and dense matrix classes,including general, symmetric, triangular, and diagonal matriceswith numeric, logical, or pattern entries. Efficient methods foroperating on such matrices, often wrapping the 'BLAS', 'LAPACK',and 'SuiteSparse' libraries. |
| License: | GPL-2 |GPL-3 | file LICENCE [expanded from: GPL (≥ 2) | file LICENCE] |
| URL: | https://Matrix.R-forge.R-project.org |
| BugReports: | https://R-forge.R-project.org/tracker/?atid=294&group_id=61 |
| Contact: | Matrix-authors@R-project.org |
| Depends: | R (≥ 4.4), methods |
| Imports: | grDevices, graphics, grid, lattice, stats, utils |
| Suggests: | MASS, datasets, sfsmisc, tools |
| Enhances: | SparseM, graph |
| LazyData: | no |
| LazyDataNote: | not possible, since we use data/*.R and our S4 classes |
| BuildResaveData: | no |
| Encoding: | UTF-8 |
| NeedsCompilation: | yes |
| Packaged: | 2025-08-27 10:17:11 UTC; maechler |
| Author: | Douglas Bates |
| Maintainer: | Martin Maechler <mmaechler+Matrix@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2025-08-28 11:50:02 UTC |
Dense Bunch-Kaufman Factorizations
Description
ClassesBunchKaufman andpBunchKaufman representBunch-Kaufman factorizations ofn \times n real,symmetric matricesA, having the general form
A = U D_{U} U' = L D_{L} L'
whereD_{U} andD_{L} are symmetric, block diagonalmatrices composed ofb_{U} andb_{L}1 \times 1 or2 \times 2 diagonal blocks;U = \prod_{k = 1}^{b_{U}} P_{k} U_{k}is the product ofb_{U} row-permuted unit upper triangularmatrices, each having nonzero entries above the diagonal in 1 or 2 columns;andL = \prod_{k = 1}^{b_{L}} P_{k} L_{k}is the product ofb_{L} row-permuted unit lower triangularmatrices, each having nonzero entries below the diagonal in 1 or 2 columns.
These classes store the nonzero entries of the2 b_{U} + 1 or2 b_{L} + 1 factors,which are individually sparse,in a dense format as a vector of lengthnn (BunchKaufman) orn(n+1)/2 (pBunchKaufman),the latter giving the “packed” representation.
Slots
Dim,Dimnamesinherited from virtual class
MatrixFactorization.uploa string, either
"U"or"L",indicating which triangle (upper or lower) of the factorizedsymmetric matrix was used to compute the factorization andin turn how thexslot is partitioned.xa numeric vector of length
n*n(BunchKaufman) orn*(n+1)/2(pBunchKaufman),wheren=Dim[1].The details of the representation are specified by the manualfor LAPACK routinesdsytrfanddsptrf.perman integer vector of length
n=Dim[1]specifying row and column interchanges as described in the manualfor LAPACK routinesdsytrfanddsptrf.
Extends
ClassBunchKaufmanFactorization, directly.ClassMatrixFactorization, by classBunchKaufmanFactorization, distance 2.
Instantiation
Objects can be generated directly by calls of the formnew("BunchKaufman", ...) ornew("pBunchKaufman", ...),but they are more typically obtained as the value ofBunchKaufman(x) forx inheriting fromdsyMatrix ordspMatrix.
Methods
coercesignature(from = "BunchKaufman", to = "dtrMatrix"):returns adtrMatrix, useful for inspectingthe internal representation of the factorization; see ‘Note’.coercesignature(from = "pBunchKaufman", to = "dtpMatrix"):returns adtpMatrix, useful for inspectingthe internal representation of the factorization; see ‘Note’.determinantsignature(from = "p?BunchKaufman", logarithm = "logical"):computes the determinant of the factorized matrixAor its logarithm.expand1signature(x = "p?BunchKaufman"):seeexpand1-methods.expand2signature(x = "p?BunchKaufman"):seeexpand2-methods.solvesignature(a = "p?BunchKaufman", b = .):seesolve-methods.
Note
InMatrix< 1.6-0, classBunchKaufman extendeddtrMatrix and classpBunchKaufman extendeddtpMatrix, reflecting the fact that the internalrepresentation of the factorization is fundamentally triangular:there aren(n+1)/2 “parameters”, and thesecan be arranged systematically to form ann \times ntriangular matrix.Matrix1.6-0 removed these extensions so that methodswould no longer be inherited fromdtrMatrix anddtpMatrix. The availability of such methods gave the wrong impression thatBunchKaufman andpBunchKaufman represent a (singular)matrix, when in fact they represent an ordered set of matrix factors.
The coercionsas(., "dtrMatrix") andas(., "dtpMatrix")are provided for users who understand the caveats.
References
The LAPACK source code, including documentation; seehttps://netlib.org/lapack/double/dsytrf.f andhttps://netlib.org/lapack/double/dsptrf.f.
Golub, G. H., & Van Loan, C. F. (2013).Matrix computations (4th ed.).Johns Hopkins University Press.doi:10.56021/9781421407944
See Also
ClassdsyMatrix and its packed counterpart.
Generic functionsBunchKaufman,expand1, andexpand2.
Examples
showClass("BunchKaufman")set.seed(1)n <- 6L(A <- forceSymmetric(Matrix(rnorm(n * n), n, n)))## With dimnames, to see that they are propagated :dimnames(A) <- rep.int(list(paste0("x", seq_len(n))), 2L)(bk.A <- BunchKaufman(A))str(e.bk.A <- expand2(bk.A, complete = FALSE), max.level = 2L)str(E.bk.A <- expand2(bk.A, complete = TRUE), max.level = 2L)## Underlying LAPACK representation(m.bk.A <- as(bk.A, "dtrMatrix"))stopifnot(identical(as(m.bk.A, "matrix"), `dim<-`(bk.A@x, bk.A@Dim)))## Number of factors is 2*b+1, b <= n, which can be nontrivial ...(b <- (length(E.bk.A) - 1L) %/% 2L)ae1 <- function(a, b, ...) all.equal(as(a, "matrix"), as(b, "matrix"), ...)ae2 <- function(a, b, ...) ae1(unname(a), unname(b), ...)## A ~ U DU U', U := prod(Pk Uk) in floating pointstopifnot(exprs = { identical(names(e.bk.A), c("U", "DU", "U.")) identical(e.bk.A[["U" ]], Reduce(`%*%`, E.bk.A[seq_len(b)])) identical(e.bk.A[["U."]], t(e.bk.A[["U"]])) ae1(A, with(e.bk.A, U %*% DU %*% U.))})## Factorization handled as factorized matrixb <- rnorm(n)stopifnot(identical(det(A), det(bk.A)), identical(solve(A, b), solve(bk.A, b)))Methods for Bunch-Kaufman Factorization
Description
Computes the Bunch-Kaufman factorization of ann \times nreal, symmetric matrixA, which has the general form
A = U D_{U} U' = L D_{L} L'
whereD_{U} andD_{L} are symmetric, block diagonalmatrices composed ofb_{U} andb_{L}1 \times 1 or2 \times 2 diagonal blocks;U = \prod_{k = 1}^{b_{U}} P_{k} U_{k}is the product ofb_{U} row-permuted unit upper triangularmatrices, each having nonzero entries above the diagonal in 1 or 2 columns;andL = \prod_{k = 1}^{b_{L}} P_{k} L_{k}is the product ofb_{L} row-permuted unit lower triangularmatrices, each having nonzero entries below the diagonal in 1 or 2 columns.
Methods are built on LAPACK routinesdsytrf anddsptrf.
Usage
BunchKaufman(x, ...)## S4 method for signature 'dsyMatrix'BunchKaufman(x, warnSing = TRUE, ...)## S4 method for signature 'dspMatrix'BunchKaufman(x, warnSing = TRUE, ...)## S4 method for signature 'matrix'BunchKaufman(x, uplo = "U", ...)Arguments
x | afinite symmetric matrix or |
warnSing | a logical indicating if awarning shouldbe signaled for singular |
uplo | a string, either |
... | further arguments passed to or from methods. |
Value
An object representing the factorization, inheriting fromvirtual classBunchKaufmanFactorization.The specific class isBunchKaufman unlessx inherits from virtual classpackedMatrix,in which case it ispBunchKaufman.
References
The LAPACK source code, including documentation; seehttps://netlib.org/lapack/double/dsytrf.f andhttps://netlib.org/lapack/double/dsptrf.f.
Golub, G. H., & Van Loan, C. F. (2013).Matrix computations (4th ed.).Johns Hopkins University Press.doi:10.56021/9781421407944
See Also
ClassesBunchKaufman andpBunchKaufman and their methods.
ClassesdsyMatrix anddspMatrix.
Generic functionsexpand1 andexpand2,for constructing matrix factors from the result.
Generic functionsCholesky,Schur,lu, andqr,for computing other factorizations.
Examples
showMethods("BunchKaufman", inherited = FALSE)set.seed(0)data(CAex, package = "Matrix")class(CAex) # dgCMatrixisSymmetric(CAex) # symmetric, but not formallyA <- as(CAex, "symmetricMatrix")class(A) # dsCMatrix## Have methods for denseMatrix (unpacked and packed),## but not yet sparseMatrix ...## Not run: (bk.A <- BunchKaufman(A))## End(Not run)(bk.A <- BunchKaufman(as(A, "unpackedMatrix")))## A ~ U DU U' in floating pointstr(e.bk.A <- expand2(bk.A), max.level = 2L)stopifnot(all.equal(as(A, "matrix"), as(Reduce(`%*%`, e.bk.A), "matrix")))Albers' example Matrix with "Difficult" Eigen Factorization
Description
An example of a sparse matrix for whicheigen() seemedto be difficult, an unscaled version of this has been posted to theweb, accompanying an E-mail to R-help(https://stat.ethz.ch/mailman/listinfo/r-help), byCasper J Albers, Open University, UK.
Usage
data(CAex)Format
This is a72 \times 72 symmetric matrix with 216non-zero entries in five bands, stored as sparse matrix of classdgCMatrix.
Details
Historical note (2006-03-30):In earlier versions ofR,eigen(CAex) fell into aninfinite loop whereaseigen(CAex, EISPACK=TRUE) had been okay.
Examples
data(CAex, package = "Matrix")str(CAex) # of class "dgCMatrix"image(CAex)# -> it's a simple band matrix with 5 bands## and the eigen values are basically 1 (42 times) and 0 (30 x):zapsmall(ev <- eigen(CAex, only.values=TRUE)$values)## i.e., the matrix is symmetric, hencesCA <- as(CAex, "symmetricMatrix")## andstopifnot(class(sCA) == "dsCMatrix", as(sCA, "matrix") == as(CAex, "matrix"))Sparse Cholesky Factorizations
Description
CHMfactor is the virtual class of sparse Choleskyfactorizations ofn \times n real, symmetricmatricesA, having the general form
P_1 A P_1' = L_1 D L_1' \overset{D_{jj} \ge 0}{=} L L'
or (equivalently)
A = P_1' L_1 D L_1' P_1 \overset{D_{jj} \ge 0}{=} P_1' L L' P_1
whereP_1 is a permutation matrix,L_1 is a unit lower triangular matrix,D is a diagonal matrix, andL = L_1 \sqrt{D}.The second equalities hold only for positive semidefiniteA,for which the diagonal entries ofD are non-negativeand\sqrt{D} is well-defined.
The implementation of classCHMfactor is based onCHOLMOD's C-levelcholmod_factor_struct. VirtualsubclassesCHMsimpl andCHMsuper separatethe simplicial and supernodal variants. These have nonvirtualsubclasses[dn]CHMsimpl and[dn]CHMsuper,where prefix ‘d’ and prefix ‘n’ are reservedfor numeric and symbolic factorizations, respectively.
Usage
isLDL(x)Arguments
x | an object inheriting from virtual class |
Value
isLDL(x) returnsTRUE orFALSE:TRUE ifx stores the lower triangular entriesofL_1-I+D,FALSE ifx stores the lower triangular entriesofL.
Slots
OfCHMfactor:
Dim,Dimnamesinherited from virtual class
MatrixFactorization.colcountan integer vector of length
Dim[1]giving anestimate of the number of nonzero entries ineach column of the lower triangular Cholesky factor.If symbolic analysis was performed prior to factorization,then the estimate is exact.perma 0-based integer vector of length
Dim[1]specifying the permutation applied to the rows and columnsof the factorized matrix.permof length 0 is valid andequivalent to the identity permutation, implying no pivoting.typean integer vector of length 6 specifyingdetails of the factorization. The elements correspond tomembers
ordering,is_ll,is_super,is_monotonic,maxcsize, andmaxesizeof the originalcholmod_factor_struct.Simplicial and supernodal factorizations are distinguishedbyis_super. Simplicial factorizations do not usemaxcsizeormaxesize. Supernodal factorizationsdo not useis_lloris_monotonic.
OfCHMsimpl (all unused bynCHMsimpl):
nzan integer vector of length
Dim[1]giving the number of nonzero entries in each column of thelower triangular Cholesky factor. There is at least onenonzero entry in each column, because the diagonal elementsof the factor are stored explicitly.pan integer vector of length
Dim[1]+1.Row indices of nonzero entries in columnjof thelower triangular Cholesky factor are obtained asi[p[j]+seq_len(nz[j])]+1.ian integer vector of length greater than or equalto
sum(nz)containing the row indices of nonzero entriesin the lower triangular Cholesky factor. These are grouped bycolumn and sorted within columns, but the columns themselvesneed not be ordered monotonically. Columns may be overallocated,i.e., the number of elements ofireserved for columnjmay exceednz[j].prv,nxtinteger vectors of length
Dim[1]+2indicating the order in which the columns ofthe lower triangular Cholesky factor are stored iniandx.Starting fromj <- Dim[1]+2,the recursionj <- nxt[j+1]+1traverses the columnsin forward order and terminates whennxt[j+1] = -1.Starting fromj <- Dim[1]+1,the recursionj <- prv[j+1]+1traverses the columnsin backward order and terminates whenprv[j+1] = -1.
OfdCHMsimpl:
xa numeric vector parallel to
icontainingthe corresponding nonzero entries of the lower triangularCholesky factorLor (if and only iftype[2]is 0) of the lower triangular matrixL_1-I+D.
OfCHMsuper:
super,pi,pxinteger vectors oflength
nsuper+1, wherensuperis the number ofsupernodes.super[j]+1is the index of the leftmostcolumn of supernodej. The row indices of supernodejare obtained ass[pi[j]+seq_len(pi[j+1]-pi[j])]+1.The numeric entries of supernodejare obtained asx[px[j]+seq_len(px[j+1]-px[j])]+1(if slotxis available).san integer vector of length greater than or equalto
Dim[1]containing the row indices of the supernodes.smay contain duplicates, but not within a supernode,where the row indices must be increasing.
OfdCHMsuper:
xa numeric vector of length less than or equal to
prod(Dim)containing the numeric entries of the supernodes.
Extends
ClassMatrixFactorization, directly.
Instantiation
Objects can be generated directly by calls of the formnew("dCHMsimpl", ...), etc., butdCHMsimpl anddCHMsuper are more typically obtained as the value ofCholesky(x, ...) forx inheriting fromsparseMatrix(oftendsCMatrix).
There is currently no API outside of calls tonewfor generatingnCHMsimpl andnCHMsuper. Theseclasses are vestigial and may be formally deprecated in a futureversion ofMatrix.
Methods
coercesignature(from = "CHMsimpl", to = "dtCMatrix"):returns adtCMatrixrepresentingthe lower triangular Cholesky factorLorthe lower triangular matrixL_1-I+D,the latter if and only iffrom@type[2]is 0.coercesignature(from = "CHMsuper", to = "dgCMatrix"):returns adgCMatrixrepresentingthe lower triangular Cholesky factorL. Note that,for supernodes spanning two or more columns, the supernodalalgorithm by design stores non-structural zeros abovethe main diagonal, hencedgCMatrixisindeed more appropriate thandtCMatrixas a coercion target.determinantsignature(from = "CHMfactor", logarithm = "logical"):behaves according to an optional argumentsqrt.Ifsqrt = FALSE, then this method computes the determinantof the factorized matrixAor its logarithm.Ifsqrt = TRUE, then this method computes the determinantof the factorL = L_1 sqrt(D)orits logarithm, givingNaNfor the modulus whenDhas negative diagonal elements. For backwards compatibility,the default value ofsqrtisTRUE, but that canbe expected change in a future version ofMatrix, hencedefensive code will always setsqrt(toTRUE,if the code must remain backwards compatible withMatrix< 1.6-0). Calls to this method not settingsqrtmay warn about the pending change. The warnings can be disabledwithoptions(Matrix.warnSqrtDefault = 0).diagsignature(x = "CHMfactor"):returns a numeric vector of lengthncontaining the diagonalelements ofD, which (if they are all non-negative)are the squared diagonal elements ofL.expandsignature(x = "CHMfactor"):seeexpand-methods.expand1signature(x = "CHMsimpl"):seeexpand1-methods.expand1signature(x = "CHMsuper"):seeexpand1-methods.expand2signature(x = "CHMsimpl"):seeexpand2-methods.expand2signature(x = "CHMsuper"):seeexpand2-methods.imagesignature(x = "CHMfactor"):seeimage-methods.nnzerosignature(x = "CHMfactor"):seennzero-methods.solvesignature(a = "CHMfactor", b = .):seesolve-methods.updatesignature(object = "CHMfactor"):returns a copy ofobjectwith the same nonzero patternbut with numeric entries updated according to additionalargumentsparentandmult, whereparentis (coercible to) adsCMatrixor adgCMatrixandmultis a numericvector of positive length.
The numeric entries are updated with those of the Choleskyfactor ofF(parent) + mult[1] * I, i.e.,F(parent)plusmult[1]times the identity matrix,whereF =identityfor symmetricparentandF =tcrossprodfor otherparent.The nonzero pattern ofF(parent)must matchthat ofSifobject = Cholesky(S, ...).updownsignature(update = ., C = ., object = "CHMfactor"):seeupdown-methods.
References
The CHOLMOD source code; seehttps://github.com/DrTimothyAldenDavis/SuiteSparse,notably the header file ‘CHOLMOD/Include/cholmod.h’definingcholmod_factor_struct.
Chen, Y., Davis, T. A., Hager, W. W., & Rajamanickam, S. (2008).Algorithm 887: CHOLMOD, supernodal sparse Cholesky factorizationand update/downdate.ACM Transactions on Mathematical Software,35(3), Article 22, 1-14.doi:10.1145/1391989.1391995
Amestoy, P. R., Davis, T. A., & Duff, I. S. (2004).Algorithm 837: AMD, an approximate minimum degree ordering algorithm.ACM Transactions on Mathematical Software,17(4), 886-905.doi:10.1145/1024074.1024081
Golub, G. H., & Van Loan, C. F. (2013).Matrix computations (4th ed.).Johns Hopkins University Press.doi:10.56021/9781421407944
See Also
ClassdsCMatrix.
Generic functionsCholesky,updown,expand1 andexpand2.
Examples
showClass("dCHMsimpl")showClass("dCHMsuper")set.seed(2)m <- 1000Ln <- 200LM <- rsparsematrix(m, n, 0.01)A <- crossprod(M)## With dimnames, to see that they are propagated :dimnames(A) <- dn <- rep.int(list(paste0("x", seq_len(n))), 2L)(ch.A <- Cholesky(A)) # pivoted, by defaultstr(e.ch.A <- expand2(ch.A, LDL = TRUE), max.level = 2L)str(E.ch.A <- expand2(ch.A, LDL = FALSE), max.level = 2L)ae1 <- function(a, b, ...) all.equal(as(a, "matrix"), as(b, "matrix"), ...)ae2 <- function(a, b, ...) ae1(unname(a), unname(b), ...)## A ~ P1' L1 D L1' P1 ~ P1' L L' P1 in floating pointstopifnot(exprs = { identical(names(e.ch.A), c("P1.", "L1", "D", "L1.", "P1")) identical(names(E.ch.A), c("P1.", "L" , "L." , "P1")) identical(e.ch.A[["P1"]], new("pMatrix", Dim = c(n, n), Dimnames = c(list(NULL), dn[2L]), margin = 2L, perm = invertPerm(ch.A@perm, 0L, 1L))) identical(e.ch.A[["P1."]], t(e.ch.A[["P1"]])) identical(e.ch.A[["L1."]], t(e.ch.A[["L1"]])) identical(E.ch.A[["L." ]], t(E.ch.A[["L" ]])) identical(e.ch.A[["D"]], Diagonal(x = diag(ch.A))) all.equal(E.ch.A[["L"]], with(e.ch.A, L1 %*% sqrt(D))) ae1(A, with(e.ch.A, P1. %*% L1 %*% D %*% L1. %*% P1)) ae1(A, with(E.ch.A, P1. %*% L %*% L. %*% P1)) ae2(A[ch.A@perm + 1L, ch.A@perm + 1L], with(e.ch.A, L1 %*% D %*% L1.)) ae2(A[ch.A@perm + 1L, ch.A@perm + 1L], with(E.ch.A, L %*% L. ))})## Factorization handled as factorized matrix## (in some cases only optionally, depending on arguments)b <- rnorm(n)stopifnot(identical(det(A), det(ch.A, sqrt = FALSE)), identical(solve(A, b), solve(ch.A, b, system = "A")))u1 <- update(ch.A, A , mult = sqrt(2))u2 <- update(ch.A, t(M), mult = sqrt(2)) # updating with crossprod(M), not Mstopifnot(all.equal(u1, u2, tolerance = 1e-14))Dense Cholesky Factorizations
Description
ClassesCholesky andpCholesky representdense, pivoted Cholesky factorizations ofn \times nreal, symmetric, positive semidefinite matricesA,having the general form
P_{1} A P_{1}' = L_{1} D L_{1}' = L L'
or (equivalently)
A = P_{1}' L_{1} D L_{1}' P_{1} = P_{1}' L L' P_{1}
whereP_{1} is a permutation matrix,L_{1} is a unit lower triangular matrix,D is a non-negative diagonal matrix, andL = L_{1} \sqrt{D}.
These classes store the entries of the Cholesky factorL or its transposeL' in a dense format asa vector of lengthnn (Cholesky) orn(n+1)/2 (pCholesky), the lattergiving the “packed” representation.
Slots
Dim,Dimnamesinherited from virtual class
MatrixFactorization.uploa string, either
"U"or"L",indicating which triangle (upper or lower) of the factorizedsymmetric matrix was used to compute the factorization andin turn whetherxstoresL'orL.xa numeric vector of length
n*n(Cholesky) orn*(n+1)/2(pCholesky),wheren=Dim[1], listing the entries of the CholeskyfactorLor its transposeL'in column-majororder.perma 1-based integer vector of length
Dim[1]specifying the permutation applied to the rows and columnsof the factorized matrix.permof length 0 is valid andequivalent to the identity permutation, implying no pivoting.
Extends
ClassCholeskyFactorization, directly.ClassMatrixFactorization, by classCholeskyFactorization, distance 2.
Instantiation
Objects can be generated directly by calls of the formnew("Cholesky", ...) ornew("pCholesky", ...),but they are more typically obtained as the value ofCholesky(x) forx inheriting fromdsyMatrix ordspMatrix(often the subclasses of those reserved for positivesemidefinite matrices, namelydpoMatrixanddppMatrix).
Methods
coercesignature(from = "Cholesky", to = "dtrMatrix"):returns adtrMatrixrepresentingthe Cholesky factorLor its transposeL';see ‘Note’.coercesignature(from = "pCholesky", to = "dtpMatrix"):returns adtpMatrixrepresentingthe Cholesky factorLor its transposeL';see ‘Note’.determinantsignature(from = "p?Cholesky", logarithm = "logical"):computes the determinant of the factorized matrixAor its logarithm.diagsignature(x = "p?Cholesky"):returns a numeric vector of lengthncontaining the diagonalelements ofD, which are the squared diagonal elements ofL.expand1signature(x = "p?Cholesky"):seeexpand1-methods.expand2signature(x = "p?Cholesky"):seeexpand2-methods.solvesignature(a = "p?Cholesky", b = .):seesolve-methods.
Note
InMatrix< 1.6-0, classCholesky extendeddtrMatrix and classpCholesky extendeddtpMatrix, reflecting the fact that the factorL is indeed a triangular matrix.Matrix1.6-0 removed these extensions so that methodswould no longer be inherited fromdtrMatrix anddtpMatrix. The availability of such methods gave the wrong impression thatCholesky andpCholesky represent a (singular)matrix, when in fact they represent an ordered set of matrix factors.
The coercionsas(., "dtrMatrix") andas(., "dtpMatrix")are provided for users who understand the caveats.
References
The LAPACK source code, including documentation; seehttps://netlib.org/lapack/double/dpstrf.f,https://netlib.org/lapack/double/dpotrf.f, andhttps://netlib.org/lapack/double/dpptrf.f.
Lucas, C. (2004).LAPACK-style codes for level 2 and 3 pivoted Cholesky factorizations.LAPACK Working Note, Number 161.https://www.netlib.org/lapack/lawnspdf/lawn161.pdf
Golub, G. H., & Van Loan, C. F. (2013).Matrix computations (4th ed.).Johns Hopkins University Press.doi:10.56021/9781421407944
See Also
ClassCHMfactor for sparse Cholesky factorizations.
ClassesdpoMatrix anddppMatrix.
Generic functionsCholesky,expand1 andexpand2.
Examples
showClass("Cholesky")set.seed(1)m <- 30Ln <- 6L(A <- crossprod(Matrix(rnorm(m * n), m, n)))## With dimnames, to see that they are propagated :dimnames(A) <- dn <- rep.int(list(paste0("x", seq_len(n))), 2L)(ch.A <- Cholesky(A)) # pivoted, by defaultstr(e.ch.A <- expand2(ch.A, LDL = TRUE), max.level = 2L)str(E.ch.A <- expand2(ch.A, LDL = FALSE), max.level = 2L)## Underlying LAPACK representation(m.ch.A <- as(ch.A, "dtrMatrix")) # which is L', not L, becauseA@uplo == "U"stopifnot(identical(as(m.ch.A, "matrix"), `dim<-`(ch.A@x, ch.A@Dim)))ae1 <- function(a, b, ...) all.equal(as(a, "matrix"), as(b, "matrix"), ...)ae2 <- function(a, b, ...) ae1(unname(a), unname(b), ...)## A ~ P1' L1 D L1' P1 ~ P1' L L' P1 in floating pointstopifnot(exprs = { identical(names(e.ch.A), c("P1.", "L1", "D", "L1.", "P1")) identical(names(E.ch.A), c("P1.", "L" , "L." , "P1")) identical(e.ch.A[["P1"]], new("pMatrix", Dim = c(n, n), Dimnames = c(list(NULL), dn[2L]), margin = 2L, perm = invertPerm(ch.A@perm))) identical(e.ch.A[["P1."]], t(e.ch.A[["P1"]])) identical(e.ch.A[["L1."]], t(e.ch.A[["L1"]])) identical(E.ch.A[["L." ]], t(E.ch.A[["L" ]])) identical(e.ch.A[["D"]], Diagonal(x = diag(ch.A))) all.equal(E.ch.A[["L"]], with(e.ch.A, L1 %*% sqrt(D))) ae1(A, with(e.ch.A, P1. %*% L1 %*% D %*% L1. %*% P1)) ae1(A, with(E.ch.A, P1. %*% L %*% L. %*% P1)) ae2(A[ch.A@perm, ch.A@perm], with(e.ch.A, L1 %*% D %*% L1.)) ae2(A[ch.A@perm, ch.A@perm], with(E.ch.A, L %*% L. ))})## Factorization handled as factorized matrixb <- rnorm(n)all.equal(det(A), det(ch.A), tolerance = 0)all.equal(solve(A, b), solve(ch.A, b), tolerance = 0)## For identical results, we need the _unpivoted_ factorization## computed by det(A) and solve(A, b)(ch.A.nopivot <- Cholesky(A, perm = FALSE))stopifnot(identical(det(A), det(ch.A.nopivot)), identical(solve(A, b), solve(ch.A.nopivot, b)))Methods for Cholesky Factorization
Description
Computes the pivoted Cholesky factorization of ann \times n real, symmetric matrixA,which has the general form
P_1 A P_1' = L_1 D L_1' \overset{D_{jj} \ge 0}{=} L L'
or (equivalently)
A = P_1' L_1 D L_1' P_1 \overset{D_{jj} \ge 0}{=} P_1' L L' P_1
whereP_1 is a permutation matrix,L_1 is a unit lower triangular matrix,D is a diagonal matrix, andL = L_1 \sqrt{D}.The second equalities hold only for positive semidefiniteA,for which the diagonal entries ofD are non-negativeand\sqrt{D} is well-defined.
Methods fordenseMatrix are built onLAPACK routinesdpstrf,dpotrf, anddpptrf.The latter two do not permute rows or columns,so thatP_1 is an identity matrix.
Methods forsparseMatrix are built onCHOLMOD routinescholmod_analyze andcholmod_factorize_p.
Usage
Cholesky(A, ...)## S4 method for signature 'dsyMatrix'Cholesky(A, perm = TRUE, tol = -1, ...)## S4 method for signature 'dspMatrix'Cholesky(A, ...)## S4 method for signature 'dsCMatrix'Cholesky(A, perm = TRUE, LDL = !super, super = FALSE, Imult = 0, ...)## S4 method for signature 'ddiMatrix'Cholesky(A, ...)## S4 method for signature 'generalMatrix'Cholesky(A, uplo = "U", ...)## S4 method for signature 'triangularMatrix'Cholesky(A, uplo = "U", ...)## S4 method for signature 'matrix'Cholesky(A, uplo = "U", ...)Arguments
A | afinite, symmetric matrix or |
perm | a logical indicating if the rows and columnsof |
tol | afinite numeric tolerance,used only if |
LDL | a logical indicating if the simplicial factorizationshould be computed as |
super | a logical indicating if the factorization shoulduse the supernodal algorithm. The alternative is the simplicialalgorithm. Setting |
Imult | afinite number. The matrixthat is factorized is |
uplo | a string, either |
... | further arguments passed to or from methods. |
Details
Note that the result of a call toCholesky inheritsfromCholeskyFactorization but notMatrix. Users who just want a matrixshould consider usingchol, whose methods aresimple wrappers aroundCholesky returning just theupper triangular Cholesky factorL',typically as atriangularMatrix.However, a more principled approach would be to constructfactors as needed from theCholeskyFactorization object,e.g., withexpand1(x, "L"), ifx is theobject.
The behaviour ofCholesky(A, perm = TRUE) for denseAis somewhat exceptional, in that it expectswithout checkingthatA is positive semidefinite. By construction, ifAis positive semidefinite and the exact algorithm encounters a zeropivot, then the unfactorized trailing submatrix is the zero matrix,and there is nothing left to do. Hence when the finite precisionalgorithm encounters a pivot less thantol, it signals awarning instead of an error and zeros the trailing submatrix inorder to guarantee thatP' L L' P is positivesemidefinite even ifA is not. It follows that one way totest for positive semidefiniteness ofA in the event of awarning is to analyze the error
\frac{\lVert A - P' L L' P \rVert}{\lVert A \rVert}\,.
See the examples and LAPACK Working Note (“LAWN”) 161for details.
Value
An object representing the factorization, inheriting fromvirtual classCholeskyFactorization.For a traditional matrixA, the specific class isCholesky.ForA inheriting fromunpackedMatrix,packedMatrix, andsparseMatrix,the specific class isCholesky,pCholesky, anddCHMsimpl ordCHMsuper,respectively.
References
The LAPACK source code, including documentation; seehttps://netlib.org/lapack/double/dpstrf.f,https://netlib.org/lapack/double/dpotrf.f, andhttps://netlib.org/lapack/double/dpptrf.f.
The CHOLMOD source code; seehttps://github.com/DrTimothyAldenDavis/SuiteSparse,notably the header file ‘CHOLMOD/Include/cholmod.h’definingcholmod_factor_struct.
Lucas, C. (2004).LAPACK-style codes for level 2 and 3 pivoted Cholesky factorizations.LAPACK Working Note, Number 161.https://www.netlib.org/lapack/lawnspdf/lawn161.pdf
Chen, Y., Davis, T. A., Hager, W. W., & Rajamanickam, S. (2008).Algorithm 887: CHOLMOD, supernodal sparse Cholesky factorizationand update/downdate.ACM Transactions on Mathematical Software,35(3), Article 22, 1-14.doi:10.1145/1391989.1391995
Amestoy, P. R., Davis, T. A., & Duff, I. S. (2004).Algorithm 837: AMD, an approximate minimum degree ordering algorithm.ACM Transactions on Mathematical Software,17(4), 886-905.doi:10.1145/1024074.1024081
Golub, G. H., & Van Loan, C. F. (2013).Matrix computations (4th ed.).Johns Hopkins University Press.doi:10.56021/9781421407944
See Also
ClassesCholesky,pCholesky,dCHMsimpl anddCHMsuperand their methods.
ClassesdpoMatrix,dppMatrix,anddsCMatrix.
Generic functionchol,for obtaining the upper triangular Cholesky factorL' as amatrix orMatrix.
Generic functionsexpand1 andexpand2,for constructing matrix factors from the result.
Generic functionsBunchKaufman,Schur,lu, andqr,for computing other factorizations.
Examples
showMethods("Cholesky", inherited = FALSE)set.seed(0)## ---- Dense ----------------------------------------------------------## .... Positive definite ..............................................n <- 6L(A1 <- crossprod(Matrix(rnorm(n * n), n, n)))(ch.A1.nopivot <- Cholesky(A1, perm = FALSE))(ch.A1 <- Cholesky(A1))stopifnot(exprs = { length(ch.A1@perm) == ncol(A1) isPerm(ch.A1@perm) is.unsorted(ch.A1@perm) # typically not the identity permutation length(ch.A1.nopivot@perm) == 0L})## A ~ P1' L D L' P1 ~ P1' L L' P1 in floating pointstr(e.ch.A1 <- expand2(ch.A1, LDL = TRUE), max.level = 2L)str(E.ch.A1 <- expand2(ch.A1, LDL = FALSE), max.level = 2L)stopifnot(exprs = { all.equal(as(A1, "matrix"), as(Reduce(`%*%`, e.ch.A1), "matrix")) all.equal(as(A1, "matrix"), as(Reduce(`%*%`, E.ch.A1), "matrix"))})## .... Positive semidefinite but not positive definite ................A2 <- A1A2[1L, ] <- A2[, 1L] <- 0A2try(Cholesky(A2, perm = FALSE)) # fails as not positive definitech.A2 <- Cholesky(A2) # returns, with a warning and ...A2.hat <- Reduce(`%*%`, expand2(ch.A2, LDL = FALSE))norm(A2 - A2.hat, "2") / norm(A2, "2") # 7.670858e-17## .... Not positive semidefinite ......................................A3 <- A1A3[1L, ] <- A3[, 1L] <- -1A3try(Cholesky(A3, perm = FALSE)) # fails as not positive definitech.A3 <- Cholesky(A3) # returns, with a warning and ...A3.hat <- Reduce(`%*%`, expand2(ch.A3, LDL = FALSE))norm(A3 - A3.hat, "2") / norm(A3, "2") # 1.781568## Indeed, 'A3' is not positive semidefinite, but 'A3.hat' _is_ch.A3.hat <- Cholesky(A3.hat)A3.hat.hat <- Reduce(`%*%`, expand2(ch.A3.hat, LDL = FALSE))norm(A3.hat - A3.hat.hat, "2") / norm(A3.hat, "2") # 1.777944e-16## ---- Sparse ---------------------------------------------------------## Really just three cases modulo permutation :#### type factorization minors of P1 A P1'## 1 simplicial P1 A P1' = L1 D L1' nonzero## 2 simplicial P1 A P1' = L L ' positive## 3 supernodal P1 A P2' = L L ' positivedata(KNex, package = "Matrix")A4 <- crossprod(KNex[["mm"]])ch.A4 <-list(pivoted = list(simpl1 = Cholesky(A4, perm = TRUE, super = FALSE, LDL = TRUE), simpl0 = Cholesky(A4, perm = TRUE, super = FALSE, LDL = FALSE), super0 = Cholesky(A4, perm = TRUE, super = TRUE )), unpivoted = list(simpl1 = Cholesky(A4, perm = FALSE, super = FALSE, LDL = TRUE), simpl0 = Cholesky(A4, perm = FALSE, super = FALSE, LDL = FALSE), super0 = Cholesky(A4, perm = FALSE, super = TRUE )))ch.A4s <- simplify2arrayrapply2 <- function(object, f, ...) rapply(object, f, , , how = "list", ...)s(rapply2(ch.A4, isLDL))s(m.ch.A4 <- rapply2(ch.A4, expand1, "L")) # giving L = L1 sqrt(D)## By design, the pivoted and simplicial factorizations## are more sparse than the unpivoted and supernodal ones ...s(rapply2(m.ch.A4, object.size))## Which is nicely visualized by lattice-based methods for 'image'inm <- c("pivoted", "unpivoted")jnm <- c("simpl1", "simpl0", "super0")for(i in 1:2) for(j in 1:3) print(image(m.ch.A4[[c(i, j)]], main = paste(inm[i], jnm[j])), split = c(j, i, 3L, 2L), more = i * j < 6L)simpl1 <- ch.A4[[c("pivoted", "simpl1")]]stopifnot(exprs = { length(simpl1@perm) == ncol(A4) isPerm(simpl1@perm, 0L) is.unsorted(simpl1@perm) # typically not the identity permutation})## One can expand with and without D regardless of isLDL(.),## but "without" requires L = L1 sqrt(D), which is conditional## on min(diag(D)) >= 0, hence "with" is the defaultisLDL(simpl1)stopifnot(min(diag(simpl1)) >= 0)str(e.ch.A4 <- expand2(simpl1, LDL = TRUE), max.level = 2L) # defaultstr(E.ch.A4 <- expand2(simpl1, LDL = FALSE), max.level = 2L)stopifnot(exprs = { all.equal(E.ch.A4[["L" ]], e.ch.A4[["L1" ]] %*% sqrt(e.ch.A4[["D"]])) all.equal(E.ch.A4[["L."]], sqrt(e.ch.A4[["D"]]) %*% e.ch.A4[["L1."]]) all.equal(A4, as(Reduce(`%*%`, e.ch.A4), "symmetricMatrix")) all.equal(A4, as(Reduce(`%*%`, E.ch.A4), "symmetricMatrix"))})## The "same" permutation matrix with "alternate" representation## [i, perm[i]] {margin=1} <-> [invertPerm(perm)[j], j] {margin=2}alt <- function(P) { P@margin <- 1L + !(P@margin - 1L) # 1 <-> 2 P@perm <- invertPerm(P@perm) P}## Expansions are elegant but inefficient (transposes are redundant)## hence programmers should consider methods for 'expand1' and 'diag'stopifnot(exprs = { identical(expand1(simpl1, "P1"), alt(e.ch.A4[["P1"]])) identical(expand1(simpl1, "L"), E.ch.A4[["L"]]) identical(Diagonal(x = diag(simpl1)), e.ch.A4[["D"]])})## chol(A, pivot = value) is a simple wrapper around## Cholesky(A, perm = value, LDL = FALSE, super = FALSE),## returning L' = sqrt(D) L1' _but_ giving no information## about the permutation P1selectMethod("chol", "dsCMatrix")stopifnot(all.equal(chol(A4, pivot = TRUE), E.ch.A4[["L."]]))## Now a symmetric matrix with positive _and_ negative eigenvalues,## hence _not_ positive semidefiniteA5 <- new("dsCMatrix", Dim = c(7L, 7L), p = c(0:1, 3L, 6:7, 10:11, 15L), i = c(0L, 0:1, 0:3, 2:5, 3:6), x = c(1, 6, 38, 10, 60, 103, -4, 6, -32, -247, -2, -16, -128, -2, -67))(ev <- eigen(A5, only.values = TRUE)$values)(t.ev <- table(factor(sign(ev), -1:1))) # the matrix "inertia"ch.A5 <- Cholesky(A5)isLDL(ch.A5)(d.A5 <- diag(ch.A5)) # diag(D) is partly negative## Sylvester's law of inertia holds here, but not in general## in finite precision arithmeticstopifnot(identical(table(factor(sign(d.A5), -1:1)), t.ev))try(expand1(ch.A5, "L")) # unable to compute L = L1 sqrt(D)try(expand2(ch.A5, LDL = FALSE)) # dittotry(chol(A5, pivot = TRUE)) # ditto## The default expansion is "square root free" and still works herestr(e.ch.A5 <- expand2(ch.A5, LDL = TRUE), max.level = 2L)stopifnot(all.equal(A5, as(Reduce(`%*%`, e.ch.A5), "symmetricMatrix")))## Version of the SuiteSparse library, which includes CHOLMODMv <- Matrix.Version()Mv[["suitesparse"]]Class "CsparseMatrix" of Sparse Matrices in Column-compressed Form
Description
The"CsparseMatrix" class is the virtual class ofall sparse matrices coded in sorted compressed column-oriented form.Since it is a virtual class, no objects may be created from it. SeeshowClass("CsparseMatrix") for its subclasses.
Slots
i:Object of class
"integer"of length nnzero(number of non-zero elements). These are the0-based row numbers foreach non-zero element in the matrix, i.e.,imust be in0:(nrow(.)-1).p:integervector for providing pointers, onefor each column, to the initial (zero-based) index of elements inthe column..@pis of lengthncol(.) + 1, withp[1] == 0andp[length(p)] == nnzero, such that infact,diff(.@p)are the number of non-zero elements foreach column.In other words,
m@p[1:ncol(m)]contains the indices ofthose elements inm@xthat are the first elements in therespective column ofm.Dim,Dimnames:inherited fromthe superclass, see the
sparseMatrixclass.
Extends
Class"sparseMatrix", directly.Class"Matrix", by class"sparseMatrix".
Methods
matrix products%*%,crossprod() andtcrossprod(),severalsolve methods,and other matrix methods available:
- Arith
signature(e1 = "CsparseMatrix", e2 = "numeric"): ...- Arith
signature(e1 = "numeric", e2 = "CsparseMatrix"): ...- Math
signature(x = "CsparseMatrix"): ...- band
signature(x = "CsparseMatrix"): ...- -
signature(e1 = "CsparseMatrix", e2 = "numeric"): ...- -
signature(e1 = "numeric", e2 = "CsparseMatrix"): ...- +
signature(e1 = "CsparseMatrix", e2 = "numeric"): ...- +
signature(e1 = "numeric", e2 = "CsparseMatrix"): ...- coerce
signature(from = "CsparseMatrix", to = "TsparseMatrix"): ...- coerce
signature(from = "CsparseMatrix", to = "denseMatrix"): ...- coerce
signature(from = "CsparseMatrix", to = "matrix"): ...- coerce
signature(from = "TsparseMatrix", to = "CsparseMatrix"): ...- coerce
signature(from = "denseMatrix", to = "CsparseMatrix"): ...- diag
signature(x = "CsparseMatrix"): ...- gamma
signature(x = "CsparseMatrix"): ...- lgamma
signature(x = "CsparseMatrix"): ...- log
signature(x = "CsparseMatrix"): ...- t
signature(x = "CsparseMatrix"): ...- tril
signature(x = "CsparseMatrix"): ...- triu
signature(x = "CsparseMatrix"): ...
Note
All classes extendingCsparseMatrix have a common validity(seevalidObject) check function. That functionadditionally checks thei slot for each column to containincreasing row numbers.
In earlier versions ofMatrix (<= 0.999375-16),validObject automatically re-sorted the entries whennecessary, and hencenew() calls with somewhat permutedi andx slots worked, asnew(...)(with slot arguments) automatically checks the validity.
Now, you have to usesparseMatrix to achieve the samefunctionality or know how to use.validateCsparse() to do so.
See Also
colSums,kronecker, and other such methodswith own help pages.
Further, the super class ofCsparseMatrix,sparseMatrix, and, e.g.,classdgCMatrix for the links to other classes.
Examples
getClass("CsparseMatrix")## The common validity check function (based on C code):getValidity(getClass("CsparseMatrix"))Construct a Diagonal Matrix
Description
Construct a formally diagonalMatrix,i.e., an object inheriting from virtual classdiagonalMatrix(or, if desired, amathematically diagonalCsparseMatrix).
Usage
Diagonal(n, x = NULL, names = FALSE).sparseDiagonal(n, x = NULL, uplo = "U", shape = "t", unitri = TRUE, kind, cols) .trDiagonal(n, x = NULL, uplo = "U", unitri = TRUE, kind) .symDiagonal(n, x = NULL, uplo = "U", kind)Arguments
n | integer indicating the dimension of the (square) matrix.If missing, then |
x | numeric or logical vector listing values for the diagonalentries, to be recycled as necessary. If |
names | either |
uplo | one of |
shape | one of |
unitri | logical indicating if a formally triangular result withones on the diagonal should be formallyunit triangular, i.e.,with |
kind | one of |
cols | optional integer vector with values in |
Value
Diagonal() returns an object inheriting from virtual classdiagonalMatrix.
.sparseDiagonal() returns aCsparseMatrixrepresentation ofDiagonal(n, x) or, ifcols is given,ofDiagonal(n, x)[, cols+1]. The precise class of the resultdepends onshape andkind.
.trDiagonal() and.symDiagonal() are simple wrappers,for.sparseDiagonal(shape = "t") and.sparseDiagonal(shape = "s"), respectively.
.sparseDiagonal() exists primarily to leverage efficientC-level methods available forCsparseMatrix.
Author(s)
Martin Maechler
See Also
the generic functiondiag forextractionof the diagonal from a matrix works for all “Matrices”.
bandSparse constructs abanded sparse matrix fromits non-zero sub-/super - diagonals.band(A) returns aband matrix containing some sub-/super - diagonals ofA.
Matrix for general matrix construction;further, classdiagonalMatrix.
Examples
Diagonal(3)Diagonal(x = 10^(3:1))Diagonal(x = (1:4) >= 2)#-> "ldiMatrix"## Use Diagonal() + kronecker() for "repeated-block" matrices:M1 <- Matrix(0+0:5, 2,3)(M <- kronecker(Diagonal(3), M1))(S <- crossprod(Matrix(rbinom(60, size=1, prob=0.1), 10,6)))(SI <- S + 10*.symDiagonal(6)) # sparse symmetric stillstopifnot(is(SI, "dsCMatrix"))(I4 <- .sparseDiagonal(4, shape="t"))# now (2012-10) unitriangularstopifnot(I4@diag == "U", all(I4 == diag(4)))Generate a Hilbert matrix
Description
Generate then byn symmetric Hilbert matrix. Becausethese matrices are ill-conditioned for moderate to largen,they are often used for testing numerical linear algebra code.
Usage
Hilbert(n)Arguments
n | a non-negative integer. |
Value
then byn symmetric Hilbert matrix as a"dpoMatrix" object.
See Also
the classdpoMatrix
Examples
Hilbert(6)Koenker-Ng Example Sparse Model Matrix and Response Vector
Description
A model matrixmm and corresponding response vectoryused in an example by Koenker and Ng. The matrixmm is a sparsematrix with 1850 rows and 712 columns but only 8758 non-zero entries.It is a"dgCMatrix" object. The vectory is justnumeric of length 1850.
Usage
data(KNex)References
Roger Koenker and Pin Ng (2003).SparseM: A sparse matrix package for R;J. of Statistical Software,8 (6),doi:10.18637/jss.v008.i06
Examples
data(KNex, package = "Matrix")class(KNex$mm)dim(KNex$mm)image(KNex$mm)str(KNex)system.time( # a fraction of a second sparse.sol <- with(KNex, solve(crossprod(mm), crossprod(mm, y))))head(round(sparse.sol,3))## Compare with QR-based solution ("more accurate, but slightly slower"):system.time( sp.sol2 <- with(KNex, qr.coef(qr(mm), y) ))all.equal(sparse.sol, sp.sol2, tolerance = 1e-13) # TRUEKhatri-Rao Matrix Product
Description
Computes Khatri-Rao products for any kind of matrices.
The Khatri-Rao product is a column-wise Kronecker product. Originallyintroduced by Khatri and Rao (1968), it has many different applications,see Liu and Trenkler (2008) for a survey. Notably, it is used inhigher-dimensional tensor decompositions, see Bader and Kolda (2008).
Usage
KhatriRao(X, Y = X, FUN = "*", sparseY = TRUE, make.dimnames = FALSE)Arguments
X,Y | matrices of with the same number of columns. |
FUN | the (name of the) |
sparseY | logical specifying if |
make.dimnames | logical indicating if the result should inherit |
Value
a"CsparseMatrix", sayR, the Khatri-Raoproduct ofX (n \times k) andY (m \times k), is of dimension(n\cdot m) \times k,where the j-th column,R[,j] is the kronecker productkronecker(X[,j], Y[,j]).
Note
The current implementation is efficient for large sparse matrices.
Author(s)
Original by Michael Cysouw, Univ. Marburg;minor tweaks, bug fixes etc, by Martin Maechler.
References
Khatri, C. G., and Rao, C. Radhakrishna (1968)Solutions to Some Functional Equations and Their Applications toCharacterization of Probability Distributions.Sankhya: Indian J. Statistics, Series A30, 167–180.
Bader, Brett W, and Tamara G Kolda (2008)Efficient MATLAB Computations with Sparse and Factored Tensors.SIAM J. Scientific Computing30, 205–231.
See Also
Examples
## Example with very small matrices:m <- matrix(1:12,3,4)d <- diag(1:4)KhatriRao(m,d)KhatriRao(d,m)dimnames(m) <- list(LETTERS[1:3], letters[1:4])KhatriRao(m,d, make.dimnames=TRUE)KhatriRao(d,m, make.dimnames=TRUE)dimnames(d) <- list(NULL, paste0("D", 1:4))KhatriRao(m,d, make.dimnames=TRUE)KhatriRao(d,m, make.dimnames=TRUE)dimnames(d) <- list(paste0("d", 10*1:4), paste0("D", 1:4))(Kmd <- KhatriRao(m,d, make.dimnames=TRUE))(Kdm <- KhatriRao(d,m, make.dimnames=TRUE))nm <- as(m, "nsparseMatrix")nd <- as(d, "nsparseMatrix")KhatriRao(nm,nd, make.dimnames=TRUE)KhatriRao(nd,nm, make.dimnames=TRUE)stopifnot(dim(KhatriRao(m,d)) == c(nrow(m)*nrow(d), ncol(d)))## border cases / checks:zm <- nm; zm[] <- FALSE # all FALSE matrixstopifnot(all(K1 <- KhatriRao(nd, zm) == 0), identical(dim(K1), c(12L, 4L)), all(K2 <- KhatriRao(zm, nd) == 0), identical(dim(K2), c(12L, 4L)))d0 <- d; d0[] <- 0; m0 <- Matrix(d0[-1,])stopifnot(all(K3 <- KhatriRao(d0, m) == 0), identical(dim(K3), dim(Kdm)), all(K4 <- KhatriRao(m, d0) == 0), identical(dim(K4), dim(Kmd)), all(KhatriRao(d0, d0) == 0), all(KhatriRao(m0, d0) == 0), all(KhatriRao(d0, m0) == 0), all(KhatriRao(m0, m0) == 0), identical(dimnames(KhatriRao(m, d0, make.dimnames=TRUE)), dimnames(Kmd)))## a matrix with "structural" and non-structural zeros:m01 <- new("dgCMatrix", i = c(0L, 2L, 0L, 1L), p = c(0L, 0L, 0L, 2L, 4L), Dim = 3:4, x = c(1, 0, 1, 0))D4 <- Diagonal(4, x=1:4) # "as" dDU <- Diagonal(4)# unit-diagonal: uplo="U"(K5 <- KhatriRao( d, m01))K5d <- KhatriRao( d, m01, sparseY=FALSE)K5Dd <- KhatriRao(D4, m01, sparseY=FALSE)K5Ud <- KhatriRao(DU, m01, sparseY=FALSE)(K6 <- KhatriRao(diag(3), t(m01)))K6D <- KhatriRao(Diagonal(3), t(m01))K6d <- KhatriRao(diag(3), t(m01), sparseY=FALSE)K6Dd <- KhatriRao(Diagonal(3), t(m01), sparseY=FALSE)stopifnot(exprs = { all(K5 == K5d) identical(cbind(c(7L, 10L), c(3L, 4L)), which(K5 != 0, arr.ind = TRUE, useNames=FALSE)) identical(K5d, K5Dd) identical(K6, K6D) all(K6 == K6d) identical(cbind(3:4, 1L), which(K6 != 0, arr.ind = TRUE, useNames=FALSE)) identical(K6d, K6Dd)})Construct a Classed Matrix
Description
Construct a Matrix of a class that inherits fromMatrix.
Usage
Matrix(data=NA, nrow=1, ncol=1, byrow=FALSE, dimnames=NULL, sparse = NULL, doDiag = TRUE, forceCheck = FALSE)Arguments
data | an optional numeric data vector or matrix. |
nrow | when |
ncol | when |
byrow | logical. If |
dimnames | a |
sparse | logical or |
doDiag | logical indicating if a Otherwise, if |
forceCheck | logical indicating if the checks for structureshould even happen when |
Details
If either ofnrow orncol is not given, an attempt ismade to infer it from the length ofdata and the otherparameter.Further,Matrix() makes efforts to keeplogicalmatrices logical, i.e., inheriting from classlMatrix,and to determine specially structured matrices such as symmetric,triangular or diagonal ones. Note that asymmetric matrix alsoneeds symmetricdimnames, e.g., by specifyingdimnames = list(NULL,NULL), see the examples.
Most of the time, the function works via a traditional (full)matrix. However,Matrix(0, nrow,ncol) directlyconstructs an “empty”sparseMatrix, as doesMatrix(FALSE, *).
Although it is sometime possible to mix unclassed matrices (createdwithmatrix) with ones of class"Matrix", it is muchsafer to always use carefully constructed ones of class"Matrix".
Value
Returns matrix of a class that inherits from"Matrix".Only ifdata is not amatrix and does not already inheritfrom classMatrix are the argumentsnrow,ncol andbyrow made use of.
See Also
The classesMatrix,symmetricMatrix,triangularMatrix, anddiagonalMatrix; further,matrix.
Special matrices can be constructed, e.g., viasparseMatrix (sparse),bdiag(block-diagonal),bandSparse (banded sparse), orDiagonal.
Examples
Matrix(0, 3, 2) # 3 by 2 matrix of zeros -> sparseMatrix(0, 3, 2, sparse=FALSE)# -> 'dense'## 4 cases - 3 different results :Matrix(0, 2, 2) # diagonal !Matrix(0, 2, 2, sparse=FALSE)# (ditto)Matrix(0, 2, 2, doDiag=FALSE)# -> sparse symm. "dsCMatrix"Matrix(0, 2, 2, sparse=FALSE, doDiag=FALSE)# -> dense symm. "dsyMatrix"Matrix(1:6, 3, 2) # a 3 by 2 matrix (+ integer warning)Matrix(1:6 + 1, nrow=3)## logical ones:Matrix(diag(4) > 0) # -> "ldiMatrix" with diag = "U"Matrix(diag(4) > 0, sparse=TRUE) # (ditto)Matrix(diag(4) >= 0) # -> "lsyMatrix" (of all 'TRUE')## triangularl3 <- upper.tri(matrix(,3,3))(M <- Matrix(l3)) # -> "ltCMatrix"Matrix(! l3) # -> "ltrMatrix"as(l3, "CsparseMatrix")# "lgCMatrix"Matrix(1:9, nrow=3, dimnames = list(c("a", "b", "c"), c("A", "B", "C")))(I3 <- Matrix(diag(3)))# identity, i.e., unit "diagonalMatrix"str(I3) # note 'diag = "U"' and the empty 'x' slot(A <- cbind(a=c(2,1), b=1:2))# symmetric *apart* from dimnamesMatrix(A) # hence 'dgeMatrix'(As <- Matrix(A, dimnames = list(NULL,NULL)))# -> symmetricforceSymmetric(A) # also symmetric, w/ symm. dimnamesstopifnot(is(As, "symmetricMatrix"), is(Matrix(0, 3,3), "sparseMatrix"), is(Matrix(FALSE, 1,1), "sparseMatrix"))Virtual Class "Matrix" of Matrices
Description
TheMatrix class is a class contained by all actualclasses in theMatrix package. It is a “virtual” class.
Slots
Diman integer vector of length 2 giving thedimensions of the matrix.
Dimnamesa list of length 2. Each element mustbe
NULLor a character vector of length equal to thecorresponding element ofDim.
Methods
- determinant
signature(x = "Matrix", logarithm = "missing"): and- determinant
signature(x = "Matrix", logarithm = "logical"):compute the (\log) determinant ofx. The methodchosen depends on the actual Matrix class ofx. Note thatdetalso works for all our matrices, calling theappropriatedeterminant()method. TheMatrix::detis an exact copy ofbase::det, but in the correctnamespace, and hence calling the S4-aware version ofdeterminant().).- diff
signature(x = "Matrix"): Asdiff()for traditional matrices, i.e., applyingdiff()to eachcolumn.- dim
signature(x = "Matrix"): extract matrix dimensionsdim.- dim<-
signature(x = "Matrix", value = "ANY"): wherevalueis integer of length 2. Allows toreshapeMatrix objects, but only whenprod(value) == prod(dim(x)).- dimnames
signature(x = "Matrix"): extractdimnames.- dimnames<-
signature(x = "Matrix", value = "list"): setthedimnamesto alistof length 2, seedimnames<-.- length
signature(x = "Matrix"): simply defined asprod(dim(x))(and hence of mode"double").- show
signature(object = "Matrix"):showmethod forprinting. For printingsparsematrices, seeprintSpMatrix.- zapsmall
signature(x = "Matrix"): typically used for"dMatrix":round()matrix entriessuch that (relatively) very small entries become zero exactly.- image
signature(object = "Matrix"): draws animageof the matrix entries, usinglevelplot()from packagelattice.- head
signature(object = "Matrix"): return only the“head”, i.e., the first few rows.- tail
signature(object = "Matrix"): return only the“tail”, i.e., the last few rows of the respective matrix.
- as.matrix, as.array
signature(x = "Matrix"): the same asas(x, "matrix"); see also the note below.- as.vector
signature(x = "Matrix", mode = "missing"):as.vector(m)should be identical toas.vector(as(m,"matrix")), implemented more efficiently for some subclasses.- as(x, "vector"), as(x, "numeric")
etc, similarly.
- coerce
signature(from = "ANY", to = "Matrix"): Thisrelies on a correctas.matrix()method forfrom.
There are many more methods that (conceptually should) work for all"Matrix" objects, e.g.,colSums,rowMeans. Evenbase functions may workautomagically (if they first callas.matrix() on theirprincipal argument), e.g.,apply,eigen,svd orkappa all do work via coercion to a“traditional” (dense)matrix.
Note
Loading theMatrix namespace “overloads”as.matrix andas.array in thebasenamespace by the equivalent offunction(x) as(x, "matrix").Consequently,as.matrix(m) oras.array(m) will properlywork whenm inherits from the"Matrix" class —also for functions in packagebase and other packages.E.g.,apply orouter can therefore be appliedto"Matrix" matrices.
Author(s)
Douglas Batesbates@stat.wisc.edu and Martin Maechler
See Also
the classesdgeMatrix,dgCMatrix, and functionMatrix for construction (and examples).
Methods, e.g., forkronecker.
Examples
slotNames("Matrix")cl <- getClass("Matrix")names(cl@subclasses) # more than 40 ..showClass("Matrix")#> output with slots and all subclasses(M <- Matrix(c(0,1,0,0), 6, 4))dim(M)diag(M)cm <- M[1:4,] + 10*Diagonal(4)diff(M)## can reshape it even :dim(M) <- c(2, 12)Mstopifnot(identical(M, Matrix(c(0,1,0,0), 2,12)), all.equal(det(cm), determinant(as(cm,"matrix"), log=FALSE)$modulus, check.attributes=FALSE))Defunct Functions in PackageMatrix
Description
The functions or variables listed here are no longer part ofMatrix as they are no longer needed.
Usage
## Defunct in 1.3-3rBind(..., deparse.level = 1)cBind(..., deparse.level = 1)Details
These either are stubs reporting that they are defunct, orhave been removed completely (apart from being documented here).
rBind andcBind were provided forR versionsolder than 3.2.0 as substitutes for thebase analoguesrbind andcbind, which at that time were not“S4-aware” and so could not be used to vertically orhorizontally concatenate"Matrix" objectstogether with traditional matrices and vectors.
See Also
Defunct,base-defunct,Matrix-deprecated
Deprecated Functions in PackageMatrix
Description
These functions are provided for compatibility with older versionsofMatrix only and may be defunct as soon as the next release.
Usage
## Deprecated in 1.5-4..2dge(from).C2nC(from, isTri).T2Cmat(from, isTri).asmatrix(x).dense2sy(from, ...).diag2mat(from).diag2sT(from, uplo = "U", kind = ".", drop0 = TRUE).diag2tT(from, uplo = "U", kind = ".", drop0 = TRUE).dsy2dsp(from).dsy2mat(from, keep.dimnames = TRUE).dxC2mat(from, chkUdiag).m2dgC(from).m2lgC(from).m2ngC(from).m2ngCn(from, na.is.not.0 = FALSE).m2ngTn(from, na.is.not.0 = FALSE).n2dgT(from).nC2d(from).nC2l(from)## Deprecated in 1.5-0## S4 method for signature 'RsparseMatrix,dgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ddenseMatrix,dgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ddiMatrix,dgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ddiMatrix,dgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ddiMatrix,dtCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgCMatrix,dgTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgCMatrix,dgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgCMatrix,dsCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgCMatrix,dtCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgCMatrix,lgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgCMatrix,ngCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgTMatrix,dgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgTMatrix,dgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgTMatrix,dsTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgTMatrix,dtCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgTMatrix,dtTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgeMatrix,dgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgeMatrix,dgTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgeMatrix,dsTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgeMatrix,dspMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgeMatrix,dsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgeMatrix,dtrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dgeMatrix,lgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsCMatrix,dgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsCMatrix,dgTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsCMatrix,dgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsCMatrix,dsRMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsCMatrix,dsTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsCMatrix,dsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsCMatrix,lsCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsCMatrix,nsCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsTMatrix,dgTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsTMatrix,dgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsTMatrix,dsCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsTMatrix,dsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsTMatrix,lsTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dspMatrix,dsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dspMatrix,lspMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsyMatrix,dsCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsyMatrix,dsTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsyMatrix,dspMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dsyMatrix,lsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtCMatrix,dgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtCMatrix,dgTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtCMatrix,dgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtCMatrix,dsCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtCMatrix,dtTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtCMatrix,dtrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtCMatrix,ltCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtCMatrix,ntCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtTMatrix,dgTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtTMatrix,dgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtTMatrix,dtCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtTMatrix,dtrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtpMatrix,dtTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtpMatrix,dtrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtpMatrix,ltpMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtrMatrix,dtpMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'dtrMatrix,ltrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'indMatrix,ngTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'indMatrix,ngeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lMatrix,dgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lgCMatrix,dgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lgCMatrix,lgTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lgCMatrix,lgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lgCMatrix,ltCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lgTMatrix,dgTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lgTMatrix,lgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lgTMatrix,lgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lgTMatrix,lsCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lgTMatrix,ltTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lgeMatrix,dgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lgeMatrix,lgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lgeMatrix,lgTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lgeMatrix,lspMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lgeMatrix,lsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lgeMatrix,ltpMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lgeMatrix,ltrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lsCMatrix,dsCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lsCMatrix,lgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lsCMatrix,lgTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lsCMatrix,lsTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lsTMatrix,lgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lsTMatrix,lgTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lsTMatrix,lsCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lsTMatrix,lsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lspMatrix,dspMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lspMatrix,lgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lspMatrix,lsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lsyMatrix,dsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lsyMatrix,lgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'lsyMatrix,lspMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ltCMatrix,lgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ltCMatrix,ltTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ltTMatrix,dtTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ltTMatrix,lgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ltTMatrix,lgTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ltTMatrix,ltCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ltTMatrix,ltrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ltpMatrix,dtpMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ltpMatrix,lgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ltpMatrix,ltrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ltrMatrix,dtrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ltrMatrix,lgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ltrMatrix,ltpMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,dgRMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,dgTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,dgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,dsCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,dsTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,dspMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,dsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,dtCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,dtTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,dtpMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,dtrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,lgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,lgTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,lgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,lsCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,lspMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,lsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,ltCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,ltTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,ltpMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,ltrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,ngCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,ngTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,ngeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,nspMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,nsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,ntCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,ntTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,ntpMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'matrix,ntrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngCMatrix,dgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngCMatrix,lgCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngCMatrix,ntCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngTMatrix,dgTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngTMatrix,lgTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngTMatrix,lgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngTMatrix,ngCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngTMatrix,ngeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngTMatrix,ntTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngeMatrix,dgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngeMatrix,lgeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngeMatrix,ngCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngeMatrix,ngTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngeMatrix,nspMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngeMatrix,nsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngeMatrix,ntpMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ngeMatrix,ntrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nsCMatrix,dsCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nsCMatrix,lsCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nsCMatrix,ngCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nsCMatrix,nsTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nsTMatrix,dsTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nsTMatrix,ngCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nsTMatrix,ngTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nsTMatrix,nsCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nsTMatrix,nsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nspMatrix,dspMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nspMatrix,lspMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nspMatrix,ngeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nspMatrix,nsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nsyMatrix,dsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nsyMatrix,lsyMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nsyMatrix,ngeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'nsyMatrix,nspMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ntCMatrix,dtCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ntCMatrix,ltCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ntCMatrix,ngCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ntTMatrix,dtTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ntTMatrix,ngCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ntTMatrix,ngTMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ntTMatrix,ntCMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ntTMatrix,ntrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ntpMatrix,dtpMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ntpMatrix,ltpMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ntpMatrix,ngeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ntpMatrix,ntrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ntrMatrix,dtrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ntrMatrix,ltrMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ntrMatrix,ngeMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'ntrMatrix,ntpMatrix'coerce(from, to, strict = TRUE)## S4 method for signature 'numLike,dgeMatrix'coerce(from, to, strict = TRUE)See Also
Deprecated,base-deprecated,Matrix-defunct
Virtual Classes Not Yet Really Implemented and Used
Description
iMatrix is the virtual class of all integer(S4) matrices. It extends theMatrix class directly.
zMatrix is the virtual class of allcomplex(S4) matrices. It extends theMatrix class directly.
Examples
showClass("iMatrix")showClass("zMatrix")The Matrix (Super-) Class of a Class
Description
Return the (maybe super-)class of classcl frompackageMatrix, returningcharacter(0) if there is none.
Usage
MatrixClass(cl, cld = getClassDef(cl), ...Matrix = TRUE, dropVirtual = TRUE, ...)Arguments
cl | string, class name |
cld | its class definition |
...Matrix |
|
dropVirtual |
|
... | further arguments are passed to |
Value
acharacter string
Author(s)
Martin Maechler, 24 Mar 2009
See Also
Matrix, the mother of allMatrix classes.
Examples
mkA <- setClass("A", contains="dgCMatrix")(A <- mkA())stopifnot(identical( MatrixClass("A"), "dgCMatrix"))Virtual Class "MatrixFactorization" of Matrix Factorizations
Description
MatrixFactorization is the virtual class offactorizations ofm \times n matricesA,having the general form
P_{1} A P_{2} = A_{1} \cdots A_{p}
or (equivalently)
A = P_{1}' A_{1} \cdots A_{p} P_{2}'
whereP_{1} andP_{2} are permutation matrices.Factorizations requiring symmetricA have the constraintP_{2} = P_{1}', and factorizations without rowor column pivoting have the constraintsP_{1} = I_{m} andP_{2} = I_{n},whereI_{m} andI_{n} are them \times m andn \times n identity matrices.
CholeskyFactorization,BunchKaufmanFactorization,SchurFactorization,LU, andQR are the virtualsubclasses ofMatrixFactorization containing all Cholesky,Bunch-Kaufman, Schur, LU, and QR factorizations, respectively.
Slots
Diman integer vector of length 2 giving thedimensions of the factorized matrix.
Dimnamesa list of length 2 preserving the
dimnamesof the factorized matrix. Each elementmust beNULLor a character vector of length equalto the corresponding element ofDim.
Methods
determinantsignature(x = "MatrixFactorization", logarithm = "missing"):setslogarithm = TRUEand recalls the generic function.dimsignature(x = "MatrixFactorization"):returnsx@Dim.dimnamessignature(x = "MatrixFactorization"):returnsx@Dimnames.dimnames<-signature(x = "MatrixFactorization", value = "NULL"):returnsxwithx@Dimnamesset tolist(NULL, NULL).dimnames<-signature(x = "MatrixFactorization", value = "list"):returnsxwithx@Dimnamesset tovalue.lengthsignature(x = "MatrixFactorization"):returnsprod(x@Dim).showsignature(object = "MatrixFactorization"):prints the internal representation of the factorization usingstr.solvesignature(a = "MatrixFactorization", b = .):seesolve-methods.unnamesignature(obj = "MatrixFactorization"):returnsobjwithobj@Dimnamesset tolist(NULL, NULL).
See Also
Classes extendingCholeskyFactorization, namelyCholesky,pCholesky,andCHMfactor.
Classes extendingBunchKaufmanFactorization, namelyBunchKaufman andpBunchKaufman.
Classes extendingSchurFactorization, namelySchur.
Classes extendingLU, namelydenseLU andsparseLU.
Classes extendingQR, namelysparseQR.
Generic functionsCholesky,BunchKaufman,Schur,lu, andqr forcomputing factorizations.
Generic functionsexpand1 andexpand2for constructing matrix factors fromMatrixFactorizationobjects.
Examples
showClass("MatrixFactorization")Class "RsparseMatrix" of Sparse Matrices in Row-compressed Form
Description
The"RsparseMatrix" class is the virtual class ofall sparse matrices coded in sorted compressed row-oriented form.Since it is a virtual class, no objects may be created from it. SeeshowClass("RsparseMatrix") for its subclasses.
Slots
j:Object of class
"integer"of lengthnnzero(number of non-zero elements). These are the row numbers foreach non-zero element in the matrix.p:Object of class
"integer"of pointers, onefor each row, to the initial (zero-based) index of elements inthe row.Dim,Dimnames:inherited fromthe superclass, see
sparseMatrix.
Extends
Class"sparseMatrix", directly.Class"Matrix", by class"sparseMatrix".
Methods
Originally,few methods were defined on purpose, as werather use theCsparseMatrix inMatrix.Then, more methods were added butbeware that thesetypically donot return"RsparseMatrix" results, butrather Csparse* or Tsparse* ones; e.g.,R[i, j] <- v for an"RsparseMatrix"R works, but after the assignment,Ris a (triplet)"TsparseMatrix".
- t
signature(x = "RsparseMatrix"): ...- coerce
signature(from = "RsparseMatrix", to = "CsparseMatrix"): ...- coerce
signature(from = "RsparseMatrix", to = "TsparseMatrix"): ...
See Also
its superclass,sparseMatrix, and, e.g., classdgRMatrix for the links to other classes.
Examples
showClass("RsparseMatrix")Schur Factorizations
Description
Schur is the class of Schur factorizations ofn \times n real matricesA,having the general form
A = Q T Q'
whereQ is an orthogonal matrix andT is a block upper triangular matrix with1 \times 1 or2 \times 2 diagonal blocksspecifying the real and complex conjugate eigenvalues ofA.The column vectors ofQ are the Schur vectors ofA,andT is the Schur form ofA.
The Schur factorization generalizes the spectral decompositionof normal matricesA, whose Schur form is block diagonal,to arbitrary square matrices.
Details
The matrixA and its Schur formT aresimilarand thus have the same spectrum. The eigenvalues are computedtrivially as the eigenvalues of the diagonal blocks ofT.
Slots
Dim,Dimnamesinherited from virtual class
MatrixFactorization.Qan orthogonal matrix,inheriting from virtual class
Matrix.Ta block upper triangular matrix,inheriting from virtual class
Matrix.The diagonal blocks have dimensions 1-by-1 or 2-by-2.EValuesa numeric or complex vector containingthe eigenvalues of the diagonal blocks of
T, which arethe eigenvalues ofTand consequently of the factorizedmatrix.
Extends
ClassSchurFactorization, directly.ClassMatrixFactorization, by classSchurFactorization, distance 2.
Instantiation
Objects can be generated directly by calls of the formnew("Schur", ...), but they are more typically obtainedas the value ofSchur(x) forx inheriting fromMatrix (oftendgeMatrix).
Methods
determinantsignature(from = "Schur", logarithm = "logical"):computes the determinant of the factorized matrixAor its logarithm.expand1signature(x = "Schur"):seeexpand1-methods.expand2signature(x = "Schur"):seeexpand2-methods.solvesignature(a = "Schur", b = .):seesolve-methods.
References
The LAPACK source code, including documentation; seehttps://netlib.org/lapack/double/dgees.f.
Golub, G. H., & Van Loan, C. F. (2013).Matrix computations (4th ed.).Johns Hopkins University Press.doi:10.56021/9781421407944
See Also
ClassdgeMatrix.
Generic functionsSchur,expand1 andexpand2.
Examples
showClass("Schur")set.seed(0)n <- 4L(A <- Matrix(rnorm(n * n), n, n))## With dimnames, to see that they are propagated :dimnames(A) <- list(paste0("r", seq_len(n)), paste0("c", seq_len(n)))(sch.A <- Schur(A))str(e.sch.A <- expand2(sch.A), max.level = 2L)## A ~ Q T Q' in floating pointstopifnot(exprs = { identical(names(e.sch.A), c("Q", "T", "Q.")) all.equal(A, with(e.sch.A, Q %*% T %*% Q.))})## Factorization handled as factorized matrixb <- rnorm(n)stopifnot(all.equal(det(A), det(sch.A)), all.equal(solve(A, b), solve(sch.A, b)))## One of the non-general cases:Schur(Diagonal(6L))Methods for Schur Factorization
Description
Computes the Schur factorization of ann \times nreal matrixA, which has the general form
A = Q T Q'
whereQ is an orthogonal matrix andT is a block upper triangular matrix with1 \times 1 and2 \times 2 diagonal blocksspecifying the real and complex conjugate eigenvalues ofA.The column vectors ofQ are the Schur vectors ofA,andT is the Schur form ofA.
Methods are built on LAPACK routinedgees.
Usage
Schur(x, vectors = TRUE, ...)Arguments
x | |
vectors | a logical. If |
... | further arguments passed to or from methods. |
Value
An object representing the factorization, inheritingfrom virtual classSchurFactorizationifvectors = TRUE. Currently, the specific classis alwaysSchur in that case.An exception is ifx is a traditional matrix,in which case the result is a named list containingQ,T, andEValues slots of theSchur object.
Ifvectors = FALSE, then the result is the samenamed list but withoutQ.
References
The LAPACK source code, including documentation; seehttps://netlib.org/lapack/double/dgees.f.
Golub, G. H., & Van Loan, C. F. (2013).Matrix computations (4th ed.).Johns Hopkins University Press.doi:10.56021/9781421407944
See Also
ClassSchur and its methods.
ClassdgeMatrix.
Generic functionsexpand1 andexpand2,for constructing matrix factors from the result.
Generic functionsCholesky,BunchKaufman,lu, andqr,for computing other factorizations.
Examples
showMethods("Schur", inherited = FALSE)set.seed(0)Schur(Hilbert(9L)) # real eigenvalues(A <- Matrix(round(rnorm(25L, sd = 100)), 5L, 5L))(sch.A <- Schur(A)) # complex eigenvalues## A ~ Q T Q' in floating pointstr(e.sch.A <- expand2(sch.A), max.level = 2L)stopifnot(all.equal(A, Reduce(`%*%`, e.sch.A)))(e1 <- eigen(sch.A@T, only.values = TRUE)$values)(e2 <- eigen( A , only.values = TRUE)$values)(e3 <- sch.A@EValues)stopifnot(exprs = { all.equal(e1, e2, tolerance = 1e-13) all.equal(e1, e3[order(Mod(e3), decreasing = TRUE)], tolerance = 1e-13) identical(Schur(A, vectors = FALSE), list(T = sch.A@T, EValues = e3)) identical(Schur(as(A, "matrix")), list(Q = as(sch.A@Q, "matrix"), T = as(sch.A@T, "matrix"), EValues = e3))})Class "TsparseMatrix" of Sparse Matrices in Triplet Form
Description
The"TsparseMatrix" class is the virtual class ofall sparse matrices coded in triplet form. Since it is a virtual class,no objects may be created from it. SeeshowClass("TsparseMatrix") for its subclasses.
Slots
Dim,Dimnames:from the
"Matrix"class,i:Object of class
"integer"- the row indicesof non-zero entriesin 0-base, i.e., must be in0:(nrow(.)-1).j:Object of class
"integer"- the columnindices of non-zero entries. Must be the same length as slotiand0-based as well, i.e., in0:(ncol(.)-1). For numeric Tsparse matrices,(i,j)pairs can occur more than once, seedgTMatrix.
Extends
Class"sparseMatrix", directly.Class"Matrix", by class"sparseMatrix".
Methods
Extraction ("[") methods, see[-methods.
Note
Most operations with sparse matrices are performed using thecompressed, column-oriented orCsparseMatrixrepresentation. The triplet representation is convenient forcreating a sparse matrix or for reading and writing suchmatrices. Once it is created, however, the matrix is generallycoerced to aCsparseMatrix for furtheroperations.
Note that allnew(.),spMatrix andsparseMatrix(*, repr="T") constructorsfor"TsparseMatrix" classes implicitly add (i.e., “sum up”)x_k's that belong to identical(i_k, j_k) pairs, see, theexample below, or also"dgTMatrix".
For convenience, methods for some operations such as%*%andcrossprod are defined forTsparseMatrix objects. These methods simplycoerce theTsparseMatrix object to aCsparseMatrix object then perform theoperation.
See Also
its superclass,sparseMatrix, and thedgTMatrix class, for the links to other classes.
Examples
showClass("TsparseMatrix")## or just the subclasses' namesnames(getClass("TsparseMatrix")@subclasses)T3 <- spMatrix(3,4, i=c(1,3:1), j=c(2,4:2), x=1:4)T3 # only 3 non-zero entries, 5 = 1+4 !Contiguity Matrix of U.S. Counties
Description
This matrix gives the contiguities of 3111 U.S. counties,using the queen criterion of at least one shared vertexor edge.
Usage
data(USCounties)Format
A3111 \times 3111 sparse, symmetricmatrix of classdsCMatrix, with 9101nonzero entries.
Source
GAL lattice file ‘usc_q.GAL’(retrieved in 2008 from‘http://sal.uiuc.edu/weights/zips/usc.zip’with permission from Luc Anselin for use and distribution)was read intoR using functionread.galfrom packagespdep.
Neighbour lists were augmented with row-standardized(and then symmetrized) spatial weights, using functionsnb2listw andsimilar.listw from packagesspdep andspatialreg.The resultinglistw object was coerced to classdsTMatrixusingas_dsTMatrix_listw fromspatialreg,and subsequently to classdsCMatrix.
References
Ord, J. K. (1975).Estimation methods for models of spatial interaction.Journal of the American Statistical Association,70(349), 120-126.doi:10.2307/2285387
Examples
data(USCounties, package = "Matrix")(n <- ncol(USCounties))I <- .symDiagonal(n)set.seed(1)r <- 50Lrho <- 1 / runif(r, 0, 0.5)system.time(MJ0 <- sapply(rho, function(mult) determinant(USCounties + mult * I, logarithm = TRUE)$modulus))## Can be done faster by updating the Cholesky factor:C1 <- Cholesky(USCounties, Imult = 2)system.time(MJ1 <- sapply(rho, function(mult) determinant(update(C1, USCounties, mult), sqrt = FALSE)$modulus))stopifnot(all.equal(MJ0, MJ1))C2 <- Cholesky(USCounties, super = TRUE, Imult = 2)system.time(MJ2 <- sapply(rho, function(mult) determinant(update(C2, USCounties, mult), sqrt = FALSE)$modulus))stopifnot(all.equal(MJ0, MJ2))Class "abIndex" of Abstract Index Vectors
Description
The"abIndex"class, short for “AbstractIndex Vector”, is used for dealing with large index vectors moreefficiently, than using integer (ornumeric) vectors ofthe kind2:1000000 orc(0:1e5, 1000:1e6).
Note that the current implementation details are subject to change,and if you consider working with these classes, please contact thepackage maintainers (packageDescription("Matrix")$Maintainer).
Objects from the Class
Objects can be created by calls of the formnew("abIndex", ...),but more easily and typically either byas(x, "abIndex") wherex is an integer (valued) vector, or directly byabIseq() and combinationc(...) of such.
Slots
kind:a
characterstring,one of("int32", "double", "rleDiff"), denoting theinternal structure of the abIndex object.x:Object of class
"numLike"; isused (i.e., not of length0) only iff the object isnotcompressed, i.e., currently exactly whenkind != "rleDiff".rleD:
Methods
- as.numeric, as.integer, as.vector
signature(x = "abIndex"): ...- [
signature(x = "abIndex", i = "index", j = "ANY", drop = "ANY"): ...- coerce
signature(from = "numeric", to = "abIndex"): ...- coerce
signature(from = "abIndex", to = "numeric"): ...- coerce
signature(from = "abIndex", to = "integer"): ...- length
signature(x = "abIndex"): ...- Ops
signature(e1 = "numeric", e2 = "abIndex"): Theseand the following arithmetic and logic operations arenot yet implemented; seeOpsfor alist of these (S4) group methods.- Ops
signature(e1 = "abIndex", e2 = "abIndex"): ...- Ops
signature(e1 = "abIndex", e2 = "numeric"): ...- Summary
signature(x = "abIndex"): ...- show
("abIndex"): simpleshowmethod,building onshow(<rleDiff>).- is.na
("abIndex"): works analogously to regular vectors.- is.finite, is.infinite
("abIndex"): ditto.
Note
This is currently experimental and not yet used for our own code.Please contact us (packageDescription("Matrix")$Maintainer),if you plan to make use of this class.
Partly builds on ideas and code from Jens Oehlschlaegel,as implemented (around 2008, in the GPL'ed part of) packageff.
See Also
rle (base) which is used here;numeric
Examples
showClass("abIndex")ii <- c(-3:40, 20:70)str(ai <- as(ii, "abIndex"))# noteai # -> show() methodstopifnot(identical(-3:20, as(abIseq1(-3,20), "vector")))Sequence Generation of "abIndex", Abstract Index Vectors
Description
Generation of abstract index vectors, i.e., objects of class"abIndex".
abIseq() is designed to work entirely likeseq,but producing"abIndex" vectors.abIseq1() is its basic building block, whereabIseq1(n,m) corresponds ton:m.
c(x, ...) will return an"abIndex" vector, whenxis one.
Usage
abIseq1(from = 1, to = 1)abIseq (from = 1, to = 1, by = ((to - from)/(length.out - 1)), length.out = NULL, along.with = NULL)## S3 method for class 'abIndex'c(...)Arguments
from,to | the starting and (maximal) end value of the sequence. |
by | number: increment of the sequence. |
length.out | desired length of the sequence. Anon-negative number, which for |
along.with | take the length from the length of this argument. |
... | in general an arbitrary number ofR objects; here,when the first is an |
Value
An abstract index vector, i.e., object of class"abIndex".
See Also
the classabIndex documentation;rep2abI() for another constructor;rle (base).
Examples
stopifnot(identical(-3:20, as(abIseq1(-3,20), "vector")))try( ## (arithmetic) not yet implementedabIseq(1, 50, by = 3))Matrix Package Methods for Function all.equal()
Description
Methods for functionall.equal() (fromR packagebase) are defined for allMatrix classes.
Methods
- target = "Matrix", current = "Matrix"
\
- target = "ANY", current = "Matrix"
\
- target = "Matrix", current = "ANY"
these three methods aresimply using
all.equal.numericdirectly and work viaas.vector().
There are more methods, notably also for"sparseVector"'s, seeshowMethods("all.equal").
Examples
showMethods("all.equal")(A <- spMatrix(3,3, i= c(1:3,2:1), j=c(3:1,1:2), x = 1:5))ex <- expand(lu. <- lu(A))stopifnot( all.equal(as(A[lu.@p + 1L, lu.@q + 1L], "CsparseMatrix"), lu.@L %*% lu.@U), with(ex, all.equal(as(P %*% A %*% t(Q), "CsparseMatrix"), L %*% U)), with(ex, all.equal(as(A, "CsparseMatrix"), t(P) %*% L %*% U %*% Q)))Standardize a Sparse Matrix in Triplet Format
Description
Detect or standardize aTsparseMatrix withunsorted or duplicated(i,j) pairs.
Usage
anyDuplicatedT(x, ...)isUniqueT(x, byrow = FALSE, isT = is(x, "TsparseMatrix"))asUniqueT(x, byrow = FALSE, isT = is(x, "TsparseMatrix"))aggregateT(x)Arguments
x | anR object. |
... | optional arguments passed to the default method forgeneric function |
byrow | a logical indicating if |
isT | a logical indicating if |
Value
anyDuplicatedT(x) returns the index of the first duplicated(i,j) pair inx (0 if there are no duplicated pairs).
isUniqueT(x) returnsTRUE ifx is aTsparseMatrix with sorted, nonduplicated(i,j) pairs andFALSE otherwise.
asUniqueT(x) returns the uniqueTsparseMatrix representation ofx withsorted, nonduplicated(i,j) pairs. Values corresponding toidentical(i,j) pairs are aggregated by addition, where in thelogical case “addition” refers to logical OR.
aggregateT(x) aggregates without sorting.
See Also
Virtual classTsparseMatrix.
Examples
example("dgTMatrix-class", echo=FALSE)## -> 'T2' with (i,j,x) slots of length 5 eachT2u <- asUniqueT(T2)stopifnot(## They "are" the same (and print the same): all.equal(T2, T2u, tol=0), ## but not internally: anyDuplicatedT(T2) == 2, anyDuplicatedT(T2u) == 0, length(T2 @x) == 5, length(T2u@x) == 3)isUniqueT(T2 ) # FALSEisUniqueT(T2u) # TRUET3 <- T2uT3[1, c(1,3)] <- 10; T3[2, c(1,5)] <- 20T3u <- asUniqueT(T3)str(T3u) # sorted in 'j', and within j, sorted in istopifnot(isUniqueT(T3u))## Logical l.TMatrix and n.TMatrix :(L2 <- T2 > 0)validObject(L2u <- asUniqueT(L2))(N2 <- as(L2, "nMatrix"))validObject(N2u <- asUniqueT(N2))stopifnot(N2u@i == L2u@i, L2u@i == T2u@i, N2@i == L2@i, L2@i == T2@i, N2u@j == L2u@j, L2u@j == T2u@j, N2@j == L2@j, L2@j == T2@j)# now with a nasty NA [partly failed in Matrix 1.1-5]:L.0N <- L.1N <- L2L.0N@x[1:2] <- c(FALSE, NA)L.1N@x[1:2] <- c(TRUE, NA)validObject(L.0N)validObject(L.1N)(m.0N <- as.matrix(L.0N))(m.1N <- as.matrix(L.1N))stopifnot(identical(10L, which(is.na(m.0N))), !anyNA(m.1N))symnum(m.0N)symnum(m.1N)Extract bands of a matrix
Description
Return the matrix obtained by setting to zero elements below a diagonal(triu), above a diagonal (tril), or outside of a generalband (band).
Usage
band(x, k1, k2, ...)triu(x, k = 0L, ...)tril(x, k = 0L, ...)Arguments
x | a matrix-like object |
k,k1,k2 | integers specifying the diagonals that are not set tozero, |
... | optional arguments passed to methods, currently unusedby packageMatrix. |
Details
triu(x, k) is equivalent toband(x, k, dim(x)[2]).Similarly,tril(x, k) is equivalent toband(x, -dim(x)[1], k).
Value
An object of a suitable matrix class, inheriting fromtriangularMatrix where appropriate.It inherits fromsparseMatrix ifand only ifx does.
Methods
- x = "CsparseMatrix"
method for compressed, sparse,column-oriented matrices.
- x = "RsparseMatrix"
method for compressed, sparse,row-oriented matrices.
- x = "TsparseMatrix"
method for sparse matrices intriplet format.
- x = "diagonalMatrix"
method for diagonal matrices.
- x = "denseMatrix"
method for dense matrices inpacked or unpacked format.
- x = "matrix"
method for traditional matricesof implicit class
matrix.
See Also
bandSparse for theconstruction of abanded sparse matrix directly from its non-zero diagonals.
Examples
## A random sparse matrix :set.seed(7)m <- matrix(0, 5, 5)m[sample(length(m), size = 14)] <- rep(1:9, length=14)(mm <- as(m, "CsparseMatrix"))tril(mm) # lower triangletril(mm, -1) # strict lower triangletriu(mm, 1) # strict upper triangleband(mm, -1, 2) # general band(m5 <- Matrix(rnorm(25), ncol = 5))tril(m5) # lower triangletril(m5, -1) # strict lower triangletriu(m5, 1) # strict upper triangleband(m5, -1, 2) # general band(m65 <- Matrix(rnorm(30), ncol = 5)) # not squaretriu(m65) # result not "dtrMatrix" unless square(sm5 <- crossprod(m65)) # symmetric band(sm5, -1, 1)# "dsyMatrix": symmetric band preserves symmetry propertyas(band(sm5, -1, 1), "sparseMatrix")# often preferable(sm <- round(crossprod(triu(mm/2)))) # sparse symmetric ("dsC*")band(sm, -1,1) # remains "dsC", *however*band(sm, -2,1) # -> "dgC"Construct Sparse Banded Matrix from (Sup-/Super-) Diagonals
Description
Construct a sparse banded matrix by specifying its non-zero sup- andsuper-diagonals.
Usage
bandSparse(n, m = n, k, diagonals, symmetric = FALSE, repr = "C", giveCsparse = (repr == "C"))Arguments
n,m | the matrix dimension |
k | integer vector of “diagonal numbers”, with identicalmeaning as in |
diagonals | optional list of sub-/super- diagonals; if missing,the result will be a pattern matrix, i.e., inheriting fromclass
|
symmetric | logical; if true the result will be symmetric(inheriting from class |
repr |
|
giveCsparse | (deprecated, replaced with |
Value
a sparse matrix (ofclassCsparseMatrix) of dimensionn \times mwith diagonal “bands” as specified.
See Also
band, forextraction of matrix bands;bdiag,diag,sparseMatrix,Matrix.
Examples
diags <- list(1:30, 10*(1:20), 100*(1:20))s1 <- bandSparse(13, k = -c(0:2, 6), diag = c(diags, diags[2]), symm=TRUE)s1s2 <- bandSparse(13, k = c(0:2, 6), diag = c(diags, diags[2]), symm=TRUE)stopifnot(identical(s1, t(s2)), is(s1,"dsCMatrix"))## a pattern Matrix of *full* (sub-)diagonals:bk <- c(0:4, 7,9)(s3 <- bandSparse(30, k = bk, symm = TRUE))## If you want a pattern matrix, but with "sparse"-diagonals,## you currently need to go via logical sparse:lLis <- lapply(list(rpois(20, 2), rpois(20, 1), rpois(20, 3))[c(1:3, 2:3, 3:2)], as.logical)(s4 <- bandSparse(20, k = bk, symm = TRUE, diag = lLis))(s4. <- as(drop0(s4), "nsparseMatrix"))n <- 1e4bk <- c(0:5, 7,11)bMat <- matrix(1:8, n, 8, byrow=TRUE)bLis <- as.data.frame(bMat)B <- bandSparse(n, k = bk, diag = bLis)Bs <- bandSparse(n, k = bk, diag = bLis, symmetric=TRUE)B [1:15, 1:30]Bs[1:15, 1:30]## can use a list *or* a matrix for specifying the diagonals:stopifnot(identical(B, bandSparse(n, k = bk, diag = bMat)), identical(Bs, bandSparse(n, k = bk, diag = bMat, symmetric=TRUE)) , inherits(B, "dtCMatrix") # triangular!)Construct a Block Diagonal Matrix
Description
Build a block diagonal matrix given several building block matrices.
Usage
bdiag(...).bdiag(lst)Arguments
... | individual matrices or a |
lst | non-empty |
Details
For non-trivial argument list,bdiag() calls.bdiag().The latter maybe useful to programmers.
Value
Asparse matrix obtained by combining the arguments into ablock diagonal matrix.
The value ofbdiag() inherits from classCsparseMatrix, whereas.bdiag() returns aTsparseMatrix.
Note
This function has been written and is efficient for the case ofrelatively few block matrices which are typically sparse themselves.
It is currentlyinefficient for the case of many small denseblock matrices.For the case ofmany densek \times k matrices,thebdiag_m() function in the ‘Examples’ is an order ofmagnitude faster.
Author(s)
Martin Maechler, built on a version posted by Berton Gunter toR-help; earlier versions have been posted by other authors, notablyScott Chasalow to S-news. Doug Bates's faster implementation buildsonTsparseMatrix objects.
See Also
Diagonal for constructing matrices ofclassdiagonalMatrix, orkroneckerwhich also works for"Matrix" inheriting matrices.
bandSparse constructs abanded sparse matrix fromits non-zero sub-/super - diagonals.
Note that other CRANR packages have own versions ofbdiag()which return traditional matrices.
Examples
bdiag(matrix(1:4, 2), diag(3))## combine "Matrix" class and traditional matrices:bdiag(Diagonal(2), matrix(1:3, 3,4), diag(3:2))mlist <- list(1, 2:3, diag(x=5:3), 27, cbind(1,3:6), 100:101)bdiag(mlist)stopifnot(identical(bdiag(mlist), bdiag(lapply(mlist, as.matrix))))ml <- c(as(matrix((1:24)%% 11 == 0, 6,4),"nMatrix"), rep(list(Diagonal(2, x=TRUE)), 3))mln <- c(ml, Diagonal(x = 1:3))stopifnot(is(bdiag(ml), "lsparseMatrix"), is(bdiag(mln),"dsparseMatrix") )## random (diagonal-)block-triangular matrices:rblockTri <- function(nb, max.ni, lambda = 3) { .bdiag(replicate(nb, { n <- sample.int(max.ni, 1) tril(Matrix(rpois(n * n, lambda = lambda), n, n)) }))}(T4 <- rblockTri(4, 10, lambda = 1))image(T1 <- rblockTri(12, 20))##' Fast version of Matrix :: .bdiag() -- for the case of *many* (k x k) matrices:##' @param lmat list(<mat1>, <mat2>, ....., <mat_N>) where each mat_j is a k x k 'matrix'##' @return a sparse (N*k x N*k) matrix of class \code{"\linkS4class{dgCMatrix}"}.bdiag_m <- function(lmat) { ## Copyright (C) 2016 Martin Maechler, ETH Zurich if(!length(lmat)) return(new("dgCMatrix")) stopifnot(is.list(lmat), is.matrix(lmat[[1]]), (k <- (d <- dim(lmat[[1]]))[1]) == d[2], # k x k all(vapply(lmat, dim, integer(2)) == k)) # all of them N <- length(lmat) if(N * k > .Machine$integer.max) stop("resulting matrix too large; would be M x M, with M=", N*k) M <- as.integer(N * k) ## result: an M x M matrix new("dgCMatrix", Dim = c(M,M), ## 'i :' maybe there's a faster way (w/o matrix indexing), but elegant? i = as.vector(matrix(0L:(M-1L), nrow=k)[, rep(seq_len(N), each=k)]), p = k * 0L:M, x = as.double(unlist(lmat, recursive=FALSE, use.names=FALSE)))}l12 <- replicate(12, matrix(rpois(16, lambda = 6.4), 4, 4), simplify=FALSE)dim(T12 <- bdiag_m(l12))# 48 x 48T12[1:20, 1:20]Boolean Arithmetic Matrix Products:%&% and Methods
Description
For boolean or “pattern” matrices, i.e.,R objects ofclassnMatrix, it is natural to allow matrixproducts using boolean instead of numerical arithmetic.
In packageMatrix, we use the binary operator%&% (aka“infix”) function) for this and provide methods for all ourmatrices and the traditionalR matrices (seematrix).
Value
a pattern matrix, i.e., inheriting from"nMatrix",or an"ldiMatrix" in case of a diagonal matrix.
Methods
We provide methods for both the “traditional” (R base) matricesand numeric vectors and conceptually all matrices andsparseVectors in packageMatrix.
signature(x = "ANY", y = "ANY")signature(x = "ANY", y = "Matrix")signature(x = "Matrix", y = "ANY")signature(x = "nMatrix", y = "nMatrix")signature(x = "nMatrix", y = "nsparseMatrix")signature(x = "nsparseMatrix", y = "nMatrix")signature(x = "nsparseMatrix", y = "nsparseMatrix")signature(x = "sparseVector", y = "sparseVector")
Note
These boolean arithmetic matrix products had been newlyintroduced forMatrix 1.2.0 (March 2015). Its implementationhas still not been tested extensively.
Originally, it was left unspecified how non-structural zeros, i.e.,0'sas part of theM@x slot should be treated for numeric("dMatrix") and logical ("lMatrix")sparse matrices. We now specify that boolean matrix products should behave as ifapplied todrop0(M), i.e., as if dropping such zeros fromthe matrix before using it.
Equivalently, for all matricesM, boolean arithmetic should work as ifapplied toM != 0 (orM != FALSE).
The current implementation ends up coercing bothx andy to(virtual) classnsparseMatrix which may be quite inefficientfor dense matrices. A future implementation may well return a matrixwithdifferent class, but the “same” content, i.e., thesame matrix entriesm_ij.
See Also
%*%,crossprod(), ortcrossprod(),for (regular) matrix product methods.
Examples
set.seed(7)L <- Matrix(rnorm(20) > 1, 4,5)(N <- as(L, "nMatrix"))L. <- L; L.[1:2,1] <- TRUE; L.@x[1:2] <- FALSE; L. # has "zeros" to drop0()D <- Matrix(round(rnorm(30)), 5,6) # -> values in -1:1 (for this seed)L %&% Dstopifnot(identical(L %&% D, N %&% D), all(L %&% D == as((L %*% abs(D)) > 0, "sparseMatrix")))## cross products , possibly with boolArith = TRUE :crossprod(N) # -> sparse patter'n' (TRUE/FALSE : boolean arithmetic)crossprod(N +0) # -> numeric Matrix (with same "pattern")stopifnot(all(crossprod(N) == t(N) %&% N), identical(crossprod(N), crossprod(N +0, boolArith=TRUE)), identical(crossprod(L), crossprod(N , boolArith=FALSE)))crossprod(D, boolArith = TRUE) # pattern: "nsCMatrix"crossprod(L, boolArith = TRUE) # dittocrossprod(L, boolArith = FALSE) # numeric: "dsCMatrix"'cbind()' and 'rbind()' recursively built on cbind2/rbind2
Description
The base functionscbind andrbind aredefined for an arbitrary number of arguments and hence have the firstformal argument.... Now, when S4 objects are found among the arguments,basecbind() andrbind() internally “dispatch”recursively, callingcbind2 orrbind2respectively, where these have methods defined and so should dispatchappropriately.
cbind2() andrbind2() are from themethods package, i.e., standardR, and have been provided forbinding togethertwo matrices, where inMatrix, we havedefined methods for these and the'Matrix' matrices.
Usage
## cbind(..., deparse.level = 1)## rbind(..., deparse.level = 1)## S4 method for signature 'Matrix,Matrix'cbind2(x, y, ...)## S4 method for signature 'Matrix,Matrix'rbind2(x, y, ...)Arguments
... | for |
deparse.level | integer controlling the construction of labelsin the case of non-matrix-like arguments; see |
x,y | vector- or matrix-likeR objects to be bound together. |
Value
typically a ‘matrix-like’ object of a similarclass as the first argument in....
Note that sometimes by default, the result is asparseMatrix if one of the arguments is (even inthe case where this is not efficient). In other cases,the result is chosen to be sparse when there are more zero entries isthan non-zero ones (as the defaultsparse inMatrix()).
Author(s)
Martin Maechler
See Also
Our class definition help pages mentioningcbind2() andrbind2() methods:"denseMatrix","diagonalMatrix","indMatrix".
Examples
(a <- matrix(c(2:1,1:2), 2,2))(M1 <- cbind(0, rbind(a, 7))) # a traditional matrixD <- Diagonal(2)(M2 <- cbind(4, a, D, -1, D, 0)) # a sparse Matrixstopifnot(validObject(M2), inherits(M2, "sparseMatrix"), dim(M2) == c(2,9))Compute the Cholesky Factor of a Matrix
Description
Computes the upper triangular Cholesky factor of ann \times n real, symmetric, positive semidefinitematrixA, optionally after pivoting.That is the factorL' in
P_{1} A P_{1}' = L L'
or (equivalently)
A = P_{1}' L L' P_{1}
whereP_{1} is a permutation matrix.
Methods fordenseMatrix are built onLAPACK routinesdpstrf,dpotrf, anddpptrf,The latter two do not permute rows or columns,so thatP_{1} is an identity matrix.
Methods forsparseMatrix are built onCHOLMOD routinescholmod_analyze andcholmod_factorize_p.
Usage
chol(x, ...)## S4 method for signature 'dsyMatrix'chol(x, pivot = FALSE, tol = -1, ...)## S4 method for signature 'dspMatrix'chol(x, ...)## S4 method for signature 'dsCMatrix'chol(x, pivot = FALSE, ...)## S4 method for signature 'ddiMatrix'chol(x, ...)## S4 method for signature 'generalMatrix'chol(x, uplo = "U", ...)## S4 method for signature 'triangularMatrix'chol(x, uplo = "U", ...)Arguments
x | afinite, symmetric, positivesemidefinite matrix or |
pivot | a logical indicating if the rows and columnsof |
tol | afinite numeric tolerance,used only if |
uplo | a string, either |
... | further arguments passed to or from methods. |
Details
Forx inheriting fromdiagonalMatrix,the diagonal result is computed directly and without pivoting,i.e., bypassing CHOLMOD.
For all otherx,chol(x, pivot = value) callsCholesky(x, perm = value, ...) under the hood.If you must know the permutationP_{1} in additionto the Cholesky factorL', then callCholeskydirectly, as the result ofchol(x, pivot = TRUE) specifiesL' but notP_{1}.
Value
A matrix,triangularMatrix,ordiagonalMatrix representingthe upper triangular Cholesky factorL'.The result is a traditional matrix ifx is atraditional matrix, dense ifx is dense, andsparse ifx is sparse.
References
The LAPACK source code, including documentation; seehttps://netlib.org/lapack/double/dpstrf.f,https://netlib.org/lapack/double/dpotrf.f, andhttps://netlib.org/lapack/double/dpptrf.f.
The CHOLMOD source code; seehttps://github.com/DrTimothyAldenDavis/SuiteSparse,notably the header file ‘CHOLMOD/Include/cholmod.h’definingcholmod_factor_struct.
Chen, Y., Davis, T. A., Hager, W. W., & Rajamanickam, S. (2008).Algorithm 887: CHOLMOD, supernodal sparse Cholesky factorizationand update/downdate.ACM Transactions on Mathematical Software,35(3), Article 22, 1-14.doi:10.1145/1391989.1391995
Amestoy, P. R., Davis, T. A., & Duff, I. S. (2004).Algorithm 837: AMD, an approximate minimum degree ordering algorithm.ACM Transactions on Mathematical Software,17(4), 886-905.doi:10.1145/1024074.1024081
Golub, G. H., & Van Loan, C. F. (2013).Matrix computations (4th ed.).Johns Hopkins University Press.doi:10.56021/9781421407944
See Also
The default method frombase,chol,called for traditional matricesx.
Generic functionCholesky, for more flexibilitynotably when computing the Choleskyfactorization andnot only thefactorL'.
Examples
showMethods("chol", inherited = FALSE)set.seed(0)## ---- Dense ----------------------------------------------------------## chol(x, pivot = value) wrapping Cholesky(x, perm = value)selectMethod("chol", "dsyMatrix")## Except in packed cases where pivoting is not yet availableselectMethod("chol", "dspMatrix")## .... Positive definite ..............................................(A1 <- new("dsyMatrix", Dim = c(2L, 2L), x = c(1, 2, 2, 5)))(R1.nopivot <- chol(A1))(R1 <- chol(A1, pivot = TRUE))## In 2-by-2 cases, we know that the permutation is 1:2 or 2:1,## even if in general 'chol' does not say ...stopifnot(exprs = { all.equal( A1 , as(crossprod(R1.nopivot), "dsyMatrix")) all.equal(t(A1[2:1, 2:1]), as(crossprod(R1 ), "dsyMatrix")) identical(Cholesky(A1)@perm, 2:1) # because 5 > 1})## .... Positive semidefinite but not positive definite ................(A2 <- new("dpoMatrix", Dim = c(2L, 2L), x = c(1, 2, 2, 4)))try(R2.nopivot <- chol(A2)) # fails as not positive definite(R2 <- chol(A2, pivot = TRUE)) # returns, with a warning and ...stopifnot(exprs = { all.equal(t(A2[2:1, 2:1]), as(crossprod(R2), "dsyMatrix")) identical(Cholesky(A2)@perm, 2:1) # because 4 > 1})## .... Not positive semidefinite ......................................(A3 <- new("dsyMatrix", Dim = c(2L, 2L), x = c(1, 2, 2, 3)))try(R3.nopivot <- chol(A3)) # fails as not positive definite(R3 <- chol(A3, pivot = TRUE)) # returns, with a warning and ...## _Not_ equal: see details and examples in help("Cholesky")all.equal(t(A3[2:1, 2:1]), as(crossprod(R3), "dsyMatrix"))## ---- Sparse ---------------------------------------------------------## chol(x, pivot = value) wrapping## Cholesky(x, perm = value, LDL = FALSE, super = FALSE)selectMethod("chol", "dsCMatrix")## Except in diagonal cases which are handled "directly"selectMethod("chol", "ddiMatrix")(A4 <- toeplitz(as(c(10, 0, 1, 0, 3), "sparseVector")))(ch.A4.nopivot <- Cholesky(A4, perm = FALSE, LDL = FALSE, super = FALSE))(ch.A4 <- Cholesky(A4, perm = TRUE, LDL = FALSE, super = FALSE))(R4.nopivot <- chol(A4))(R4 <- chol(A4, pivot = TRUE))det4 <- det(A4)b4 <- rnorm(5L)x4 <- solve(A4, b4)stopifnot(exprs = { identical(R4.nopivot, expand1(ch.A4.nopivot, "L.")) identical(R4, expand1(ch.A4, "L.")) all.equal(A4, crossprod(R4.nopivot)) all.equal(A4[ch.A4@perm + 1L, ch.A4@perm + 1L], crossprod(R4)) all.equal(diag(R4.nopivot), sqrt(diag(ch.A4.nopivot))) all.equal(diag(R4), sqrt(diag(ch.A4))) all.equal(sqrt(det4), det(R4.nopivot)) all.equal(sqrt(det4), det(R4)) all.equal(det4, det(ch.A4.nopivot, sqrt = FALSE)) all.equal(det4, det(ch.A4, sqrt = FALSE)) all.equal(x4, solve(R4.nopivot, solve(t(R4.nopivot), b4))) all.equal(x4, solve(ch.A4.nopivot, b4)) all.equal(x4, solve(ch.A4, b4))})Inverse from Cholesky Factor
Description
Givenformally upper and lower triangular matricesU andL, compute(U' U)^{-1}and(L L')^{-1}, respectively.
This function can be seen as way to compute the inverse of asymmetric positive definite matrix given its Cholesky factor.Equivalently, it can be seen as a way to compute(X' X)^{-1} given theR part of theQR factorization ofX, ifR is constrained to havepositive diagonal entries.
Usage
chol2inv(x, ...)## S4 method for signature 'dtrMatrix'chol2inv(x, ...)## S4 method for signature 'dtCMatrix'chol2inv(x, ...)## S4 method for signature 'generalMatrix'chol2inv(x, uplo = "U", ...)Arguments
x | a square matrix or |
uplo | a string, either |
... | further arguments passed to or from methods. |
Value
A matrix,symmetricMatrix,ordiagonalMatrix representingthe inverse of the positive definite matrix whoseCholesky factor isx.The result is a traditional matrix ifx is atraditional matrix, dense ifx is dense, andsparse ifx is sparse.
See Also
The default method frombase,chol2inv,called for traditional matricesx.
Generic functionchol, for computing the uppertriangular Cholesky factorL' of a symmetric positivesemidefinite matrix.
Generic functionsolve, for solving linear systemsand (as a corollary) for computing inverses more generally.
Examples
(A <- Matrix(cbind(c(1, 1, 1), c(1, 2, 4), c(1, 4, 16))))(R <- chol(A))(L <- t(R))(R2i <- chol2inv(R))(L2i <- chol2inv(R))stopifnot(exprs = { all.equal(R2i, tcrossprod(solve(R))) all.equal(L2i, crossprod(solve(L))) all.equal(as(R2i %*% A, "matrix"), diag(3L)) # the identity all.equal(as(L2i %*% A, "matrix"), diag(3L)) # ditto})Sparse Matrix Coercion from and to those from packageSparseM
Description
Methods for coercion from and to sparse matrices from packageSparseMare provided here, for ease of porting functionality to theMatrix package, and comparing functionality of the twopackages. All these work via the usualas(., "<class>")coercion,
as(from, Class)
Methods
- from = "matrix.csr", to = "dgRMatrix"
...
- from = "matrix.csc", to = "dgCMatrix"
...
- from = "matrix.coo", to = "dgTMatrix"
...
- from = "dgRMatrix", to = "matrix.csr"
...
- from = "dgCMatrix", to = "matrix.csc"
...
- from = "dgTMatrix", to = "matrix.coo"
...
- from = "Matrix", to = "matrix.csr"
...
- from = "matrix.csr", to = "dgCMatrix"
...
- from = "matrix.coo", to = "dgCMatrix"
...
- from = "matrix.csr", to = "Matrix"
...
- from = "matrix.csc", to = "Matrix"
...
- from = "matrix.coo", to = "Matrix"
...
See Also
The documentation in CRAN packageSparseM, such asSparseM.ontology, and one important class,matrix.csr.
Conversions "graph" <–> (sparse) Matrix
Description
Since 2005, packageMatrix has supported coercions to andfrom classgraph from packagegraph.Since 2013, this functionality has been exposed via functionsT2graph andgraph2T, which, unlike methods foras(from, "<Class>"), support optional arguments.
Usage
graph2T(from, use.weights = )T2graph(from, need.uniq = !isUniqueT(from), edgemode = NULL)Arguments
from | for |
use.weights | logical indicating if weights should be used, i.e.,equivalently the result will be numeric, i.e. of class |
need.uniq | a logical indicating if |
edgemode | one of |
Value
Forgraph2T(), a sparse matrix inheriting from"TsparseMatrix".
ForT2graph() anR object of class"graph".
See Also
Packageigraph, which provides similar coercionsto and from its classigraph via functionsgraph_from_adjacency_matrix andas_adjacency_matrix.
Examples
if(requireNamespace("graph")) { n4 <- LETTERS[1:4]; dns <- list(n4,n4) show(a1 <- sparseMatrix(i= c(1:4), j=c(2:4,1), x = 2, dimnames=dns)) show(g1 <- as(a1, "graph")) # directed unlist(graph::edgeWeights(g1)) # all '2' show(a2 <- sparseMatrix(i= c(1:4,4), j=c(2:4,1:2), x = TRUE, dimnames=dns)) show(g2 <- as(a2, "graph")) # directed # now if you want it undirected: show(g3 <- T2graph(as(a2,"TsparseMatrix"), edgemode="undirected")) show(m3 <- as(g3,"Matrix")) show( graph2T(g3) ) # a "pattern Matrix" (nsTMatrix) a. <- sparseMatrix(i=4:1, j=1:4, dimnames=list(n4, n4), repr="T") # no 'x' show(a.) # "ngTMatrix" show(g. <- as(a., "graph"))}Form Row and Column Sums and Means
Description
Form row and column sums and means forobjects, forsparseMatrix the result mayoptionally be sparse (sparseVector), too.Row or column names are kept respectively as forbase matricesandcolSums methods, when the result isnumeric vector.
Usage
colSums(x, na.rm = FALSE, dims = 1L, ...) rowSums(x, na.rm = FALSE, dims = 1L, ...)colMeans(x, na.rm = FALSE, dims = 1L, ...)rowMeans(x, na.rm = FALSE, dims = 1L, ...)## S4 method for signature 'CsparseMatrix' colSums(x, na.rm = FALSE, dims = 1L, sparseResult = FALSE, ...)## S4 method for signature 'CsparseMatrix' rowSums(x, na.rm = FALSE, dims = 1L, sparseResult = FALSE, ...)## S4 method for signature 'CsparseMatrix'colMeans(x, na.rm = FALSE, dims = 1L, sparseResult = FALSE, ...)## S4 method for signature 'CsparseMatrix'rowMeans(x, na.rm = FALSE, dims = 1L, sparseResult = FALSE, ...)Arguments
x | a Matrix, i.e., inheriting from |
na.rm | logical. Should missing values (including |
dims | completely ignored by the |
... | potentially further arguments, for method |
sparseResult | logical indicating if the result should be sparse,i.e., inheriting from class |
Value
returns a numeric vector ifsparseResult isFALSE as perdefault. Otherwise, returns asparseVector.
dimnames(x) are only kept (asnames(v))when the resultingv isnumeric, sincesparseVectors do not have names.
See Also
colSums and thesparseVector classes.
Examples
(M <- bdiag(Diagonal(2), matrix(1:3, 3,4), diag(3:2))) # 7 x 8colSums(M)d <- Diagonal(10, c(0,0,10,0,2,rep(0,5)))MM <- kronecker(d, M)dim(MM) # 70 80length(MM@x) # 160, but many are '0' ; drop those:MM <- drop0(MM)length(MM@x) # 32 cm <- colSums(MM)(scm <- colSums(MM, sparseResult = TRUE))stopifnot(is(scm, "sparseVector"), identical(cm, as.numeric(scm)))rowSums (MM, sparseResult = TRUE) # 14 of 70 are not zerocolMeans(MM, sparseResult = TRUE) # 16 of 80 are not zero## Since we have no 'NA's, these two are equivalent :stopifnot(identical(rowMeans(MM, sparseResult = TRUE), rowMeans(MM, sparseResult = TRUE, na.rm = TRUE)), rowMeans(Diagonal(16)) == 1/16, colSums(Diagonal(7)) == 1)## dimnames(x) --> names( <value> ) :dimnames(M) <- list(paste0("r", 1:7), paste0("V",1:8))McolSums(M)rowMeans(M)## Assertions :stopifnot(exprs = { all.equal(colSums(M), structure(c(1,1,6,6,6,6,3,2), names = colnames(M))) all.equal(rowMeans(M), structure(c(1,1,4,8,12,3,2)/8, names = paste0("r", 1:7)))})Compute Approximate CONDition number and 1-Norm of (Large) Matrices
Description
“Estimate”, i.e. compute approximately the CONDition number ofa (potentially large, often sparse) matrixA.It works by apply a fastrandomized approximation of the 1-norm,norm(A,"1"), throughonenormest(.).
Usage
condest(A, t = min(n, 5), normA = norm(A, "1"), silent = FALSE, quiet = TRUE)onenormest(A, t = min(n, 5), A.x, At.x, n, silent = FALSE, quiet = silent, iter.max = 10, eps = 4 * .Machine$double.eps)Arguments
A | a square matrix, optional for |
t | number of columns to use in the iterations. |
normA | number; (an estimate of) the 1-norm of |
silent | logical indicating if warning and (by default)convergence messages should be displayed. |
quiet | logical indicating if convergence messages should bedisplayed. |
A.x,At.x | when |
n |
|
iter.max | maximal number of iterations for the 1-norm estimator. |
eps | the relative change that is deemed irrelevant. |
Details
condest() callslu(A), and subsequentlyonenormest(A.x = , At.x = ) to compute an approximate norm oftheinverse ofA,A^{-1}, in a way whichkeeps using sparse matrices efficiently whenA is sparse.
Note thatonenormest() uses random vectors and henceboth functions' results are random, i.e., depend on the randomseed, see, e.g.,set.seed().
Value
Both functions return alist;condest() with components,
est | a number |
v | the maximal |
The functiononenormest() returns a list with components,
est | a number |
v | 0-1 integer vector length |
w | numeric vector, the largest |
iter | the number of iterations used. |
Author(s)
This is based on octave'scondest() andonenormest() implementations with original authorJason Riedy, U Berkeley; translation toR andadaption by Martin Maechler.
References
Nicholas J. Higham and Françoise Tisseur (2000).A Block Algorithm for Matrix 1-Norm Estimation, with an Applicationto 1-Norm Pseudospectra.SIAM J. Matrix Anal. Appl.21, 4, 1185–1201.
William W. Hager (1984).Condition Estimates.SIAM J. Sci. Stat. Comput.5, 311–316.
See Also
Examples
data(KNex, package = "Matrix")mtm <- with(KNex, crossprod(mm))system.time(ce <- condest(mtm))sum(abs(ce$v)) ## || v ||_1 == 1## Prove that || A v || = || A || / est (as ||v|| = 1):stopifnot(all.equal(norm(mtm %*% ce$v), norm(mtm) / ce$est))## reciprocal1 / ce$estsystem.time(rc <- rcond(mtm)) # takes ca 3 x longerrcall.equal(rc, 1/ce$est) # TRUE -- the approximation was goodone <- onenormest(mtm)str(one) ## est = 12.3## the maximal column:which(one$v == 1) # mostly 4, rarely 1, depending on random seed(Virtual) Class "dMatrix" of "double" Matrices
Description
ThedMatrix class is a virtual class contained by all actualclasses of numeric matrices in theMatrix package. Similarly,all the actual classes of logical matrices inherit from thelMatrix class.
Slots
Common toall matrix object in the package:
Dim:Object of class
"integer"- the dimensionsof the matrix - must be an integer vector with exactly twonon-negative values.Dimnames:list of length two; each componentcontaining NULL or a
charactervector lengthequal the correspondingDimelement.
Methods
There are (relatively simple) group methods (see, e.g.,Arith)
- Arith
signature(e1 = "dMatrix", e2 = "dMatrix"): ...- Arith
signature(e1 = "dMatrix", e2 = "numeric"): ...- Arith
signature(e1 = "numeric", e2 = "dMatrix"): ...- Math
signature(x = "dMatrix"): ...- Math2
signature(x = "dMatrix", digits = "numeric"):this group containsround()andsignif().- Compare
signature(e1 = "numeric", e2 = "dMatrix"): ...- Compare
signature(e1 = "dMatrix", e2 = "numeric"): ...- Compare
signature(e1 = "dMatrix", e2 = "dMatrix"): ...- Summary
signature(x = "dMatrix"): The"Summary"group contains the seven functionsmax(),min(),range(),prod(),sum(),any(), andall().
The following methods are also defined for all double matrices:
- expm
signature(x = "dMatrix"): computes the“Matrix Exponential”, seeexpm.
The following methods are defined for all logical matrices:
- which
signature(x = "lsparseMatrix")and many othersubclasses of"lMatrix": as thebase functionwhich(x, arr.ind)returns the indices of theTRUEentries inx; ifarr.indis true,as a 2-column matrix of row and column indices. SinceMatrixversion 1.2-9, ifuseNamesis true, as by default, withdimnames, the same asbase::which.
See Also
The nonzero-pattern matrix classnMatrix, whichcan be used to store non-NAlogicalmatrices even more compactly.
The numeric matrix classesdgeMatrix,dgCMatrix, andMatrix.
drop0(x, tol=1e-10) is sometimes preferable to (andmore efficient than)zapsmall(x, digits=10).
Examples
showClass("dMatrix") set.seed(101) round(Matrix(rnorm(28), 4,7), 2) M <- Matrix(rlnorm(56, sd=10), 4,14) (M. <- zapsmall(M)) table(as.logical(M. == 0))Virtual Class "ddenseMatrix" of Numeric Dense Matrices
Description
This is the virtual class of all dense numeric (i.e.,double, hence“ddense”) S4 matrices.
Its most important subclass is thedgeMatrix class.
Extends
Class"dMatrix" directly;class"Matrix", by the above.
Slots
the same slots at its subclassdgeMatrix, seethere.
Methods
Most methods are implemented viaas(*, "generalMatrix") and aremainly used as “fallbacks” when the subclass doesn't need itsown specialized method.
UseshowMethods(class = "ddenseMatrix", where = "package:Matrix") for an overview.
See Also
The virtual classesMatrix,dMatrix, anddsparseMatrix.
Examples
showClass("ddenseMatrix")showMethods(class = "ddenseMatrix", where = "package:Matrix")Class "ddiMatrix" of Diagonal Numeric Matrices
Description
The class"ddiMatrix" of numerical diagonal matrices.Note that diagonal matrices now extendsparseMatrix, whereasthey did extend dense matrices earlier.
Objects from the Class
Objects can be created by calls of the formnew("ddiMatrix", ...)but typically rather viaDiagonal.
Slots
x:numeric vector. For an
n \times nmatrix, thexslot is of lengthnor0,depending on thediagslot:diag:"character"string, either"U"or"N"where"U"denotes unit-diagonal, i.e., identitymatrices.Dim,Dimnames:matrix dimension and
dimnames, see theMatrixclassdescription.
Extends
Class"diagonalMatrix", directly.Class"dMatrix", directly.Class"sparseMatrix", indirectly, seeshowClass("ddiMatrix").
Methods
- %*%
signature(x = "ddiMatrix", y = "ddiMatrix"): ...
See Also
ClassdiagonalMatrix and functionDiagonal.
Examples
(d2 <- Diagonal(x = c(10,1)))str(d2)## slightly larger in internal size:str(as(d2, "sparseMatrix"))M <- Matrix(cbind(1,2:4))M %*% d2 #> `fast' multiplicationchol(d2) # trivialstopifnot(is(cd2 <- chol(d2), "ddiMatrix"), all.equal(cd2@x, c(sqrt(10),1)))Dense LU Factorizations
Description
denseLU is the class of dense, row-pivoted LU factorizationsofm \times n real matricesA,having the general form
P_{1} A = L U
or (equivalently)
A = P_{1}' L U
whereP_{1} is anm \times m permutation matrix,L is anm \times \min(m,n)unit lower trapezoidal matrix, andU is a\min(m,n) \times nupper trapezoidal matrix. Ifm = n, then the factorsL andU are triangular.
Slots
Dim,Dimnamesinherited from virtual class
MatrixFactorization.xa numeric vector of length
prod(Dim)storingthe triangularLandUfactors together in a packedformat. The details of the representation are specified by themanual for LAPACK routinedgetrf.perman integer vector of length
min(Dim)specifying the permutationP_{1}as a product oftranspositions. The corresponding permutation vector canbe obtained asasPerm(perm).
Extends
ClassLU, directly.ClassMatrixFactorization, by classLU, distance 2.
Instantiation
Objects can be generated directly by calls of the formnew("denseLU", ...), but they are more typically obtainedas the value oflu(x) forx inheriting fromdenseMatrix (oftendgeMatrix).
Methods
coercesignature(from = "denseLU", to = "dgeMatrix"):returns adgeMatrixwith the dimensionsof the factorized matrixA, equal toLbelow thediagonal and equal toUon and above the diagonal.determinantsignature(from = "denseLU", logarithm = "logical"):computes the determinant of the factorized matrixAor its logarithm.expandsignature(x = "denseLU"):seeexpand-methods.expand1signature(x = "denseLU"):seeexpand1-methods.expand2signature(x = "denseLU"):seeexpand2-methods.solvesignature(a = "denseLU", b = "missing"):seesolve-methods.
References
The LAPACK source code, including documentation; seehttps://netlib.org/lapack/double/dgetrf.f.
Golub, G. H., & Van Loan, C. F. (2013).Matrix computations (4th ed.).Johns Hopkins University Press.doi:10.56021/9781421407944
See Also
ClasssparseLU for sparse LU factorizations.
ClassdgeMatrix.
Generic functionslu,expand1 andexpand2.
Examples
showClass("denseLU")set.seed(1)n <- 3L(A <- Matrix(round(rnorm(n * n), 2L), n, n))## With dimnames, to see that they are propagated :dimnames(A) <- dn <- list(paste0("r", seq_len(n)), paste0("c", seq_len(n)))(lu.A <- lu(A))str(e.lu.A <- expand2(lu.A), max.level = 2L)## Underlying LAPACK representation(m.lu.A <- as(lu.A, "dgeMatrix")) # which is L and U interlacedstopifnot(identical(as(m.lu.A, "matrix"), `dim<-`(lu.A@x, lu.A@Dim)))ae1 <- function(a, b, ...) all.equal(as(a, "matrix"), as(b, "matrix"), ...)ae2 <- function(a, b, ...) ae1(unname(a), unname(b), ...)## A ~ P1' L U in floating pointstopifnot(exprs = { identical(names(e.lu.A), c("P1.", "L", "U")) identical(e.lu.A[["P1."]], new( "pMatrix", Dim = c(n, n), Dimnames = c(dn[1L], list(NULL)), margin = 1L, perm = invertPerm(asPerm(lu.A@perm)))) identical(e.lu.A[["L"]], new("dtrMatrix", Dim = c(n, n), Dimnames = list(NULL, NULL), uplo = "L", diag = "U", x = lu.A@x)) identical(e.lu.A[["U"]], new("dtrMatrix", Dim = c(n, n), Dimnames = c(list(NULL), dn[2L]), uplo = "U", diag = "N", x = lu.A@x)) ae1(A, with(e.lu.A, P1. %*% L %*% U)) ae2(A[asPerm(lu.A@perm), ], with(e.lu.A, L %*% U))})## Factorization handled as factorized matrixb <- rnorm(n)stopifnot(identical(det(A), det(lu.A)), identical(solve(A, b), solve(lu.A, b)))Virtual Class "denseMatrix" of All Dense Matrices
Description
This is the virtual class of all dense (S4) matrices.It partitions into two subclassespackedMatrix andunpackedMatrix.Alternatively into the (currently) three subclassesddenseMatrix,ldenseMatrix, andndenseMatrix.
denseMatrix is (hence) the direct superclass of these (2+3 = 5) classes.
Extends
class"Matrix" directly.
Slots
exactly those of its superclass"Matrix", i.e.,"Dim" and"Dimnames".
Methods
UseshowMethods(class = "denseMatrix", where = "package:Matrix") for an overview of methods.
Extraction ("[") methods,see[-methods.
See Also
colSums,kronecker, and other such methodswith own help pages.
Its superclassMatrix, and main subclasses,ddenseMatrix andsparseMatrix.
Examples
showClass("denseMatrix")Compressed, sparse, column-oriented numeric matrices
Description
ThedgCMatrix class is a class of sparse numericmatrices in the compressed, sparse, column-oriented format. In thisimplementation the non-zero elements in the columns are sorted intoincreasing row order.dgCMatrix is the“standard” class for sparse numeric matrices in theMatrix package.
Objects from the Class
Objects can be created by calls of the formnew("dgCMatrix", ...), more typically viaas(*, "CsparseMatrix") or similar.Often however, more easily viaMatrix(*, sparse = TRUE),or most efficiently viasparseMatrix().
Slots
x:Object of class
"numeric"- the non-zeroelements of the matrix.- ...
all other slots are inherited from the superclass
"CsparseMatrix".
Methods
Matrix products (e.g.,crossprod-methods), and (among other)
- coerce
signature(from = "matrix", to = "dgCMatrix")- diag
signature(x = "dgCMatrix"): returns the diagonalofx- dim
signature(x = "dgCMatrix"): returns the dimensionsofx- image
signature(x = "dgCMatrix"): plots an image ofxusing thelevelplotfunction- solve
signature(a = "dgCMatrix", b = "..."):seesolve-methods, notably the extra argumentsparse.- lu
signature(x = "dgCMatrix"): computes the LUdecomposition of a squaredgCMatrixobject
See Also
Examples
(m <- Matrix(c(0,0,2:0), 3,5))str(m)m[,1]Sparse Compressed, Row-oriented Numeric Matrices
Description
ThedgRMatrix class is a class of sparse numericmatrices in the compressed, sparse, row-oriented format. In thisimplementation the non-zero elements in the rows are sorted intoincreasing column order.
Note: The column-oriented sparse classes, e.g.,dgCMatrix, are preferred and better supported intheMatrix package.
Objects from the Class
Objects can be created by calls of the formnew("dgRMatrix", ...).
Slots
j:Object of class
"integer"of length nnzero(number of non-zero elements). These are the column numbers foreach non-zero element in the matrix.p:Object of class
"integer"of pointers, onefor each row, to the initial (zero-based) index of elements inthe row.x:Object of class
"numeric"- the non-zeroelements of the matrix.Dim:Object of class
"integer"- the dimensionsof the matrix.
Methods
- diag
signature(x = "dgRMatrix"): returns the diagonalofx- dim
signature(x = "dgRMatrix"): returns the dimensionsofx- image
signature(x = "dgRMatrix"): plots an image ofxusing thelevelplotfunction
See Also
theRsparseMatrix class, the virtual class of allsparse compressedrow-oriented matrices, with its methods.ThedgCMatrix class (column compressedsparse) is really preferred.
Sparse matrices in triplet form
Description
The"dgTMatrix" class is the class of sparsematrices stored as (possibly redundant) triplets. The internalrepresentation is not at all unique, contrary to the one for classdgCMatrix.
Objects from the Class
Objects can be created by calls of the formnew("dgTMatrix", ...), but more typically viaspMatrix() orsparseMatrix(*, repr = "T").
Slots
i:integerrow indices of non-zeroentriesin 0-base, i.e., must be in0:(nrow(.)-1).j:integercolumn indices of non-zeroentries. Must be the same length as slotiand0-based as well, i.e., in0:(ncol(.)-1).x:numericvector - the (non-zero)entry at position(i,j). Must be the same length as sloti. If an index pair occurs more than once, the correspondingvalues of slotxare added to form the element of the matrix.Dim:Object of class
"integer"of length 2 -the dimensions of the matrix.
Methods
- +
signature(e1 = "dgTMatrix", e2 = "dgTMatrix")- image
signature(x = "dgTMatrix"): plots an image ofxusing thelevelplotfunction- t
signature(x = "dgTMatrix"): returns the transpose ofx
Note
Triplet matrices are a convenient form in which to construct sparsematrices after which they can be coerced todgCMatrix objects.
Note that bothnew(.) andspMatrix constructorsfor"dgTMatrix" (and other"TsparseMatrix"classes) implicitly addx_k's that belong to identical(i_k, j_k) pairs.
However this means that a matrix typically can be stored in more thanone possible"TsparseMatrix" representations.UseasUniqueT() in order to ensure uniqueness of theinternal representation of such a matrix.
See Also
ClassdgCMatrix or the superclassesdsparseMatrix andTsparseMatrix;asUniqueT.
Examples
m <- Matrix(0+1:28, nrow = 4)m[-3,c(2,4:5,7)] <- m[ 3, 1:4] <- m[1:3, 6] <- 0(mT <- as(m, "TsparseMatrix"))str(mT)mT[1,]mT[4, drop = FALSE]stopifnot(identical(mT[lower.tri(mT)], m [lower.tri(m) ]))mT[lower.tri(mT,diag=TRUE)] <- 0mT## Triplet representation with repeated (i,j) entries## *adds* the corresponding x's:T2 <- new("dgTMatrix", i = as.integer(c(1,1,0,3,3)), j = as.integer(c(2,2,4,0,0)), x=10*1:5, Dim=4:5)str(T2) # contains (i,j,x) slots exactly as above, butT2 ## has only three non-zero entries, as for repeated (i,j)'s, ## the corresponding x's are "implicitly" addedstopifnot(nnzero(T2) == 3)Class "dgeMatrix" of Dense Numeric (S4 Class) Matrices
Description
A general numeric dense matrix in the S4 Matrixrepresentation.dgeMatrix is the“standard”class for dense numeric matrices in theMatrix package.
Objects from the Class
Objects can be created by calls of the formnew("dgeMatrix", ...)or, more commonly, by coercion from theMatrix class (seeMatrix) or byMatrix(..).
Slots
x:Object of class
"numeric"- the numericvalues contained in the matrix, in column-major order.Dim:Object of class
"integer"- the dimensionsof the matrix - must be an integer vector with exactly twonon-negative values.Dimnames:a list of length two - inherited from class
Matrix.factors:Object of class
"list"- a listof factorizations of the matrix.
Methods
The are group methods (see, e.g.,Arith)
- Arith
signature(e1 = "dgeMatrix", e2 = "dgeMatrix"): ...- Arith
signature(e1 = "dgeMatrix", e2 = "numeric"): ...- Arith
signature(e1 = "numeric", e2 = "dgeMatrix"): ...- Math
signature(x = "dgeMatrix"): ...- Math2
signature(x = "dgeMatrix", digits = "numeric"): ...
matrix products%*%,crossprod() andtcrossprod(),severalsolve methods,and other matrix methods available:
- Schur
signature(x = "dgeMatrix", vectors = "logical"): ...- Schur
signature(x = "dgeMatrix", vectors = "missing"): ...- chol
signature(x = "dgeMatrix"): seechol.- colMeans
signature(x = "dgeMatrix"): columnwise means (averages)- colSums
signature(x = "dgeMatrix"): columnwise sums- diag
signature(x = "dgeMatrix"): ...- dim
signature(x = "dgeMatrix"): ...- dimnames
signature(x = "dgeMatrix"): ...- eigen
signature(x = "dgeMatrix", only.values= "logical"): ...- eigen
signature(x = "dgeMatrix", only.values= "missing"): ...- norm
signature(x = "dgeMatrix", type = "character"): ...- norm
signature(x = "dgeMatrix", type = "missing"): ...- rcond
signature(x = "dgeMatrix", norm = "character")ornorm = "missing":the reciprocal condition number,rcond().- rowMeans
signature(x = "dgeMatrix"): rowwise means (averages)- rowSums
signature(x = "dgeMatrix"): rowwise sums- t
signature(x = "dgeMatrix"): matrix transpose
See Also
ClassesMatrix,dtrMatrix, anddsyMatrix.
Transform Triangular Matrices from Unit Triangular to General Triangular and Back
Description
Transform a triangular matrixx, i.e., ofclasstriangularMatrix,from (internally!) unit triangular (“unitriangular”) to“general” triangular (diagU2N(x)) or back (diagN2U(x)).Note that the latter,diagN2U(x), also sets the diagonal to onein cases wherediag(x) was not all one.
.diagU2N(x) and.diagN2U(x) assumewithoutchecking thatx is atriangularMatrix withsuitablediag slot ("U" and"N", respectively),hence they should be used with care.
Usage
diagU2N(x, cl = getClassDef(class(x)), checkDense = FALSE) diagN2U(x, cl = getClassDef(class(x)), checkDense = FALSE).diagU2N(x, cl = getClassDef(class(x)), checkDense = FALSE).diagN2U(x, cl = getClassDef(class(x)), checkDense = FALSE)Arguments
x | a |
cl | (optional, for speedup only:) class (definition) of |
checkDense | logical indicating if dense (see |
Details
The concept of unit triangular matrices with adiag slot of"U" stems from LAPACK.
Value
a triangular matrix of the sameclass but with adifferentdiag slot. FordiagU2N (semantically) withidentical entries asx, whereas indiagN2U(x), theoff-diagonal entries are unchanged and the diagonal is set to all1 even if it was not previously.
Note
Such internal storage details should rarely be of relevance to theuser. Hence, these functions really are ratherinternalutilities.
See Also
"triangularMatrix","dtCMatrix".
Examples
(T <- Diagonal(7) + triu(Matrix(rpois(49, 1/4), 7, 7), k = 1))(uT <- diagN2U(T)) # "unitriangular"(t.u <- diagN2U(10*T))# changes the diagonal!stopifnot(all(T == uT), diag(t.u) == 1, identical(T, diagU2N(uT)))T[upper.tri(T)] <- 5 # still "dtC"T <- diagN2U(as(T,"triangularMatrix"))dT <- as(T, "denseMatrix") # (unitriangular)dT.n <- diagU2N(dT, checkDense = TRUE)sT.n <- diagU2N(dT)stopifnot(is(dT.n, "denseMatrix"), is(sT.n, "sparseMatrix"), dT@diag == "U", dT.n@diag == "N", sT.n@diag == "N", all(dT == dT.n), all(dT == sT.n))Class "diagonalMatrix" of Diagonal Matrices
Description
Class "diagonalMatrix" is the virtual class of all diagonal matrices.
Objects from the Class
A virtual Class: No objects may becreated from it.
Slots
diag:characterstring, either"U"or"N", where"U"means ‘unit-diagonal’.Dim:matrix dimension, and
Dimnames:the
dimnames, alist, see theMatrixclassdescription. Typicallylist(NULL,NULL)for diagonal matrices.
Extends
Class"sparseMatrix", directly.
Methods
These are just a subset of the signature for which defined methods.Currently, there are (too) many explicit methods defined in order toensure efficient methods for diagonal matrices.
- coerce
signature(from = "matrix", to = "diagonalMatrix"): ...- coerce
signature(from = "Matrix", to = "diagonalMatrix"): ...- coerce
signature(from = "diagonalMatrix", to = "generalMatrix"): ...- coerce
signature(from = "diagonalMatrix", to = "triangularMatrix"): ...- coerce
signature(from = "diagonalMatrix", to = "nMatrix"): ...- coerce
signature(from = "diagonalMatrix", to = "matrix"): ...- coerce
signature(from = "diagonalMatrix", to = "sparseVector"): ...- t
signature(x = "diagonalMatrix"): ...
and many more methods
- solve
signature(a = "diagonalMatrix", b, ...): istrivially implemented, of course; see alsosolve-methods.- which
signature(x = "nMatrix"), semanticallyequivalent tobase functionwhich(x, arr.ind).- "Math"
signature(x = "diagonalMatrix"): all thesegroup methods return a"diagonalMatrix", apart fromcumsum()etc which return avector also forbasematrix.- *
signature(e1 = "ddiMatrix", e2="denseMatrix"):arithmetic and other operators from theOpsgroup have a few dozen explicit method definitions, in order tokeep the resultsdiagonal in many cases, including the following:- /
signature(e1 = "ddiMatrix", e2="denseMatrix"):the result is from classddiMatrixwhich istypically very desirable. Note that whene2containsoff-diagonal zeros orNAs, we implicitly use0 / x = 0, hencediffering from traditionalR arithmetic (where0 / 0\mapsto \mbox{NaN}), in order to preserve sparsity.- summary
(object = "diagonalMatrix"): Returnsan object of S3 class"diagSummary"which is the summary ofthe vectorobject@xplus a simple heading, and anappropriateprintmethod.
See Also
Diagonal() as constructor of these matrices, andisDiagonal.ddiMatrix andldiMatrix are“actual” classes extending"diagonalMatrix".
Examples
I5 <- Diagonal(5)D5 <- Diagonal(x = 10*(1:5))## trivial (but explicitly defined) methods:stopifnot(identical(crossprod(I5), I5), identical(tcrossprod(I5), I5), identical(crossprod(I5, D5), D5), identical(tcrossprod(D5, I5), D5), identical(solve(D5), solve(D5, I5)), all.equal(D5, solve(solve(D5)), tolerance = 1e-12) )solve(D5)# efficient as is diagonal# an unusual way to construct a band matrix:rbind2(cbind2(I5, D5), cbind2(D5, I5))Scale the Rows and Columns of a Matrix
Description
dimScale,rowScale, andcolScale implementD1 %*% x %*% D2,D %*% x, andx %*% Dfor diagonal matricesD1,D2, andD withdiagonal entriesd1,d2, andd, respectively.Unlike the explicit products, these functions preservedimnames(x)and symmetry where appropriate.
Usage
dimScale(x, d1 = sqrt(1/diag(x, names = FALSE)), d2 = d1)rowScale(x, d)colScale(x, d)Arguments
x | a matrix, possibly inheriting from virtual class |
d1,d2,d | numeric vectors giving factors by which to scalethe rows or columns of |
Details
dimScale(x) (withd1 andd2 unset) is onlyroughly equivalent tocov2cor(x).cov2corsets the diagonal entries of the result to 1 (exactly);dimScale does not.
Value
The result of scalingx, currently always inheriting fromvirtual classdMatrix.
It inherits fromtriangularMatrix if and onlyifx does. In the special case ofdimScale(x, d1, d2)with identicald1 andd2, it inherits fromsymmetricMatrix if and only ifx does.
Author(s)
Mikael Jagan
See Also
Examples
n <- 6L(x <- forceSymmetric(matrix(1, n, n)))dimnames(x) <- rep.int(list(letters[seq_len(n)]), 2L)d <- seq_len(n)(D <- Diagonal(x = d))(scx <- dimScale(x, d)) # symmetry and 'dimnames' kept(mmx <- D %*% x %*% D) # symmetry and 'dimnames' loststopifnot(identical(unname(as(scx, "generalMatrix")), mmx))rowScale(x, d)colScale(x, d)Dulmage-Mendelsohn Permutation / Decomposition
Description
For anyn \times m (typically) sparse matrixxcompute the Dulmage-Mendelsohn row and columns permutations which atfirst splits then rows andm columns into coarse partitionseach; and then a finer one, reordering rows and columns such that thepermutated matrix is “as upper triangular” as possible.
Usage
dmperm(x, nAns = 6L, seed = 0L)Arguments
x | a typically sparse matrix; internally coerced to either |
nAns | an integer specifying the |
seed | an integer code in -1,0,1; determining the (initial)permutation; by default, |
Details
See the book section by Tim Davis; page 122–127, in the References.
Value
a namedlist with (by default) 6 components,
p | integer vector with the permutation |
q | integer vector with the permutation |
r | integer vector of length |
s | integer vector of length |
rr5 | integer vector of length 5, defining the coarse rowdecomposition. |
cc5 | integer vector of length 5, defining the coarse column decomposition. |
Author(s)
Martin Maechler, with a lot of “encouragement” by MauricioVargas.
References
Section 7.4Dulmage-Mendelsohn decomposition, pp. 122 ff of
Timothy A. Davis (2006)Direct Methods for Sparse Linear Systems, SIAM Series“Fundamentals of Algorithms”.
See Also
Schur, the class of permutation matrices;"pMatrix".
Examples
set.seed(17)(S9 <- rsparsematrix(9, 9, nnz = 10, symmetric=TRUE)) # dsCMatrixstr( dm9 <- dmperm(S9) )(S9p <- with(dm9, S9[p, q]))## looks good, but *not* quite upper triangular; these, too:str( dm9.0 <- dmperm(S9, seed=-1)) # non-random too.str( dm9_1 <- dmperm(S9, seed= 1)) # a random one## The last two permutations differ, but have the same effect!(S9p0 <- with(dm9.0, S9[p, q])) # .. hmm ..stopifnot(all.equal(S9p0, S9p))# same as as default, but different from the random oneset.seed(11)(M <- triu(rsparsematrix(9,11, 1/4)))dM <- dmperm(M); with(dM, M[p, q])(Mp <- M[sample.int(nrow(M)), sample.int(ncol(M))])dMp <- dmperm(Mp); with(dMp, Mp[p, q])set.seed(7)(n7 <- rsparsematrix(5, 12, nnz = 10, rand.x = NULL))str( dm.7 <- dmperm(n7) )stopifnot(exprs = { lengths(dm.7[1:2]) == dim(n7) identical(dm.7, dmperm(as(n7, "dMatrix"))) identical(dm.7[1:4], dmperm(n7, nAns=4)) identical(dm.7[1:2], dmperm(n7, nAns=2))})Positive Semi-definite Dense (Packed | Non-packed) Numeric Matrices
Description
The
"dpoMatrix"class is the class ofpositive-semidefinite symmetric matrices in nonpacked storage.The
"dppMatrix"class is the same except in packedstorage. Only the upper triangle or the lower triangle isrequired to be available.The
"corMatrix"and"copMatrix"classesrepresent correlation matrices. They extend"dpoMatrix"and"dppMatrix", respectively, with an additional slotsdallowing restoration of the original covariance matrix.
Objects from the Class
Objects can be created by calls of theformnew("dpoMatrix", ...) or fromcrossprod applied toan"dgeMatrix" object.
Slots
uplo:Object of class
"character". Must beeither "U", for upper triangular, and "L", for lower triangular.x:Object of class
"numeric". The numericvalues that constitute the matrix, stored in column-major order.Dim:Object of class
"integer". The dimensionsof the matrix which must be a two-element vector of non-negativeintegers.Dimnames:inherited from class
"Matrix"factors:Object of class
"list". A namedlist of factorizations that have been computed for the matrix.sd:(for
"corMatrix"and"copMatrix")anumericvector of lengthncontaining the(original)\sqrt{var(.)}entries which allowreconstruction of a covariance matrix from the correlation matrix.
Extends
Class"dsyMatrix", directly.
Classes"dgeMatrix","symmetricMatrix", and many moreby class"dsyMatrix".
Methods
- chol
signature(x = "dpoMatrix"):Returns (and stores) the Cholesky decomposition ofx, seechol.- determinant
signature(x = "dpoMatrix"):Returns thedeterminantofx, viachol(x), see above.- rcond
signature(x = "dpoMatrix", norm = "character"):Returns (and stores) the reciprocal of the condition number ofx. Thenormcan be"O"for theone-norm (the default) or"I"for the infinity-norm. Forsymmetric matrices the result does not depend on the norm.- solve
signature(a = "dpoMatrix", b = "...."), and- solve
signature(a = "dppMatrix", b = "....")workvia the Cholesky composition, see also the Matrixsolve-methods.- Arith
signature(e1 = "dpoMatrix", e2 = "numeric")(andquite a few other signatures): The result of (“elementwise”defined) arithmetic operations is typicallynotpositive-definite anymore. The only exceptions, currently, aremultiplications, divisions or additions withpositivelength(.) == 1numbers (orlogicals).
Note
Currently the validity methods for these classes such asgetValidity(getClass("dpoMatrix")) for efficiency reasonsonly check the diagonal entries of the matrix – they may not be negative.This is only necessary but not sufficient for a symmetric matrix to bepositive semi-definite.
A more reliable (but often more expensive) check for positivesemi-definiteness would look at the signs ofdiag(BunchKaufman(.))(with some tolerance for very small negative values), and for (strict)positive definiteness at something like!inherits(tryCatch(chol(.), error=identity), "error") .Indeed, whencoercing to these classes, a versionofCholesky() orchol() istypically used, e.g., seeselectMethod("coerce", c(from="dsyMatrix", to="dpoMatrix")) .
See Also
ClassesdsyMatrix anddgeMatrix;further,Matrix,rcond,chol,solve,crossprod.
Examples
h6 <- Hilbert(6)rcond(h6)str(h6)h6 * 27720 # is ``integer''solve(h6)str(hp6 <- pack(h6))### Note that as(*, "corMatrix") *scales* the matrix(ch6 <- as(h6, "corMatrix"))stopifnot(all.equal(as(h6 * 27720, "dsyMatrix"), round(27720 * h6), tolerance = 1e-14), all.equal(ch6@sd^(-2), 2*(1:6)-1, tolerance = 1e-12))chch <- Cholesky(ch6, perm = FALSE)stopifnot(identical(chch, ch6@factors$Cholesky), all(abs(crossprod(as(chch, "dtrMatrix")) - ch6) < 1e-10))Drop Non-Structural Zeros from a Sparse Matrix
Description
Deletes “non-structural” zeros (i.e., zeros stored explicitly,in memory) from a sparse matrix and returns the result.
Usage
drop0(x, tol = 0, is.Csparse = NA, give.Csparse = TRUE)Arguments
x | a |
tol | a non-negative number. If |
is.Csparse | a logical used only if |
give.Csparse | a logical indicating if the result mustinherit from virtual class |
Value
AsparseMatrix, the result of deletingnon-structural zeros fromx, possibly after coercion.
Note
drop0 is sometimes called in conjunction withzapsmall, e.g., when dealing with sparsematrix products; see the example.
See Also
FunctionsparseMatrix, for constructing objectsinheriting from virtual classsparseMatrix;nnzero.
Examples
(m <- sparseMatrix(i = 1:8, j = 2:9, x = c(0:2, 3:-1), dims = c(10L, 20L)))drop0(m)## A larger example:t5 <- new("dtCMatrix", Dim = c(5L, 5L), uplo = "L", x = c(10, 1, 3, 10, 1, 10, 1, 10, 10), i = c(0L,2L,4L, 1L, 3L,2L,4L, 3L, 4L), p = c(0L, 3L, 5L, 7:9))TT <- kronecker(t5, kronecker(kronecker(t5, t5), t5))IT <- solve(TT)I. <- TT %*% IT ; nnzero(I.) # 697 ( == 625 + 72 )I.0 <- drop0(zapsmall(I.))## which actually can be more efficiently achieved byI.. <- drop0(I., tol = 1e-15)stopifnot(all(I.0 == Diagonal(625)), nnzero(I..) == 625)Numeric Symmetric Sparse (column compressed) Matrices
Description
ThedsCMatrix class is a class of symmetric, sparsenumeric matrices in the compressed,column-oriented format. Inthis implementation the non-zero elements in the columns are sortedinto increasing row order.
ThedsTMatrix class is the class of symmetric, sparse numericmatrices intriplet format.
Objects from the Class
Objects can be created by calls of the formnew("dsCMatrix", ...) ornew("dsTMatrix", ...), or automatically via e.g.,as(*, "symmetricMatrix"), or (fordsCMatrix) alsofromMatrix(.).
Creation “from scratch” most efficiently happens viasparseMatrix(*, symmetric=TRUE).
Slots
uplo:A character object indicating if the uppertriangle (
"U") or the lower triangle ("L") is stored.i:Object of class
"integer"of length nnZ(half number of non-zero elements). These are the rownumbers for each non-zero element in the lower triangle of the matrix.p:(only in class
"dsCMatrix":) anintegervector for providing pointers, one for eachcolumn, see the detailed description inCsparseMatrix.j:(only in class
"dsTMatrix":) Object ofclass"integer"of length nnZ (asi). These are thecolumn numbers for each non-zero element in the lower triangle ofthe matrix.x:Object of class
"numeric"of length nnZ –the non-zero elements of the matrix (to be duplicated for full matrix).factors:Object of class
"list"- a listof factorizations of the matrix.Dim:Object of class
"integer"- the dimensionsof the matrix - must be an integer vector with exactly twonon-negative values.
Extends
Both classes extend classes andsymmetricMatrixdsparseMatrix directly;dsCMatrix further directly extendsCsparseMatrix, wheredsTMatrix doesTsparseMatrix.
Methods
- solve
signature(a = "dsCMatrix", b = "...."):x<- solve(a,b)solvesA x = bforx; seesolve-methods.- chol
signature(x = "dsCMatrix", pivot = "logical"):Returns (and stores) the Cholesky decomposition ofx, seechol.- Cholesky
signature(A = "dsCMatrix",...):Computes more flexibly Cholesky decompositions,seeCholesky.- determinant
signature(x = "dsCMatrix", logarithm ="missing"): Evaluate the determinant ofxon thelogarithm scale. This creates and stores the Cholesky factorization.- determinant
signature(x = "dsCMatrix", logarithm ="logical"): Evaluate the determinant ofxon thelogarithm scale or not, according to thelogarithmargument. This creates and stores the Cholesky factorization.- t
signature(x = "dsCMatrix"): Transpose. As for allsymmetric matrices, a matrix for which the upper triangle isstored produces a matrix for which the lower triangle is storedand vice versa, i.e., theuploslot is swapped, and the rowand column indices are interchanged.- t
signature(x = "dsTMatrix"): Transpose. Theuploslot is swapped from"U"to"L"or viceversa, as for a"dsCMatrix", see above.
See Also
ClassesdgCMatrix,dgTMatrix,dgeMatrix and those mentioned above.
Examples
mm <- Matrix(toeplitz(c(10, 0, 1, 0, 3)), sparse = TRUE)mm # automatically dsCMatrixstr(mm)mT <- as(as(mm, "generalMatrix"), "TsparseMatrix")## Either(symM <- as(mT, "symmetricMatrix")) # dsT(symC <- as(symM, "CsparseMatrix")) # dsC## orsT <- Matrix(mT, sparse=TRUE, forceCheck=TRUE) # dsTsym2 <- as(symC, "TsparseMatrix")## --> the same as 'symM', a "dsTMatrix"Symmetric Sparse Compressed Row Matrices
Description
ThedsRMatrix class is a class of symmetric, sparsematrices in the compressed, row-oriented format. In thisimplementation the non-zero elements in the rows are sorted intoincreasing column order.
Objects from the Class
These"..RMatrix" classes are currently still mostly unimplemented!
Objects can be created by calls of the formnew("dsRMatrix", ...).
Slots
uplo:A character object indicating if the uppertriangle (
"U") or the lower triangle ("L") isstored. At present only the lower triangle form is allowed.j:Object of class
"integer"of lengthnnzero(number of non-zero elements). These are the rownumbers for each non-zero element in the matrix.p:Object of class
"integer"of pointers, onefor each row, to the initial (zero-based) index of elements inthe row.factors:Object of class
"list"- a listof factorizations of the matrix.x:Object of class
"numeric"- the non-zeroelements of the matrix.Dim:Object of class
"integer"- the dimensionsof the matrix - must be an integer vector with exactly twonon-negative values.Dimnames:List of length two, see
Matrix.
Extends
ClassesdsparseMatrix,symmetricMatrix, andRsparseMatrix, directly.
Class"dMatrix", by class"dsparseMatrix";class"sparseMatrix", by classes"dsparseMatrix" and"RsparseMatrix".
Methods
- forceSymmetric
signature(x = "dsRMatrix", uplo = "missing"):a trivial method just returningx- forceSymmetric
signature(x = "dsRMatrix", uplo = "character"):ifuplo == x@uplo, this trivially returnsx;otherwiset(x).
See Also
the classesdgCMatrix,dgTMatrix, anddgeMatrix.
Examples
(m0 <- new("dsRMatrix"))m2 <- new("dsRMatrix", Dim = c(2L,2L), x = c(3,1), j = c(1L,1L), p = 0:2)m2stopifnot(colSums(as(m2, "TsparseMatrix")) == 3:4)str(m2)(ds2 <- forceSymmetric(diag(2))) # dsy*dR <- as(ds2, "RsparseMatrix")dR # dsRMatrixVirtual Class "dsparseMatrix" of Numeric Sparse Matrices
Description
The Class"dsparseMatrix" is the virtual (super) class ofall numeric sparse matrices.
Slots
Dim:the matrix dimension, see class
"Matrix".Dimnames:see the
"Matrix"class.x:a
numericvector containing the(non-zero) matrix entries.
Extends
Class"dMatrix" and"sparseMatrix", directly.
Class"Matrix", by the above classes.
See Also
the documentation of the (non virtual) sub classes, seeshowClass("dsparseMatrix"); in particular,dgTMatrix,dgCMatrix, anddgRMatrix.
Examples
showClass("dsparseMatrix")Symmetric Dense (Packed or Unpacked) Numeric Matrices
Description
The
"dsyMatrix"class is the class of symmetric, dense matricesinnon-packed storage and"dspMatrix"is the class of symmetric dense matrices inpacked storage, seepack(). Only the uppertriangle or the lower triangle is stored.
Objects from the Class
Objects can be created by calls of the formnew("dsyMatrix", ...) ornew("dspMatrix", ...), respectively.
Slots
uplo:Object of class
"character". Must beeither "U", for upper triangular, and "L", for lower triangular.x:Object of class
"numeric". The numericvalues that constitute the matrix, stored in column-major order.Dim,Dimnames:The dimension (a length-2
"integer") and corresponding names (orNULL), see theMatrix.factors:Object of class
"list". A namedlist of factorizations that have been computed for the matrix.
Extends
"dsyMatrix" extends class"dgeMatrix", directly, whereas"dspMatrix" extends class"ddenseMatrix", directly.
Both extend class"symmetricMatrix", directly,and class"Matrix" and others,indirectly, useshowClass("dsyMatrix"), e.g., for details.
Methods
- norm
signature(x = "dspMatrix", type = "character"), orx = "dsyMatrix"ortype = "missing": Computes thematrix norm of the desired type, see,norm.- rcond
signature(x = "dspMatrix", type = "character"), orx = "dsyMatrix"ortype = "missing": Computes thereciprocal condition number,rcond().- solve
signature(a = "dspMatrix", b = "...."), and- solve
signature(a = "dsyMatrix", b = "...."):x<- solve(a,b)solvesA x = bforx; seesolve-methods.- t
signature(x = "dsyMatrix"): Transpose; swaps fromupper triangular to lower triangular storage, i.e., the uplo slotfrom"U"to"L"or vice versa, the same as for allsymmetric matrices.
See Also
Thepositive (Semi-)definite dense (packed or non-packednumeric matrix classesdpoMatrix,dppMatrix andcorMatrix,
ClassesdgeMatrix andMatrix;solve,norm,rcond,t
Examples
## Only upper triangular part matters (when uplo == "U" as per default)(sy2 <- new("dsyMatrix", Dim = as.integer(c(2,2)), x = c(14, NA,32,77)))str(t(sy2)) # uplo = "L", and the lower tri. (i.e. NA is replaced).chol(sy2) #-> "Cholesky" matrix(sp2 <- pack(sy2)) # a "dspMatrix"## Coercing to dpoMatrix gives invalid object:sy3 <- new("dsyMatrix", Dim = as.integer(c(2,2)), x = c(14, -1, 2, -7))try(as(sy3, "dpoMatrix")) # -> error: not positive definite## 4x4 examplem <- matrix(0,4,4); m[upper.tri(m)] <- 1:6(sym <- m+t(m)+diag(11:14, 4))(S1 <- pack(sym))(S2 <- t(S1))stopifnot(all(S1 == S2)) # equal "seen as matrix", but differ internally :str(S1)S2@xTriangular, (compressed) sparse column matrices
Description
The"dtCMatrix" class is a class of triangular, sparsematrices in the compressed, column-oriented format. In thisimplementation the non-zero elements in the columns are sorted intoincreasing row order.
The"dtTMatrix" class is a class of triangular, sparse matricesin triplet format.
Objects from the Class
Objects can be created by calls of the formnew("dtCMatrix", ...) or calls of the formnew("dtTMatrix", ...),but more typically automatically viaMatrix()or coercions such asas(x, "triangularMatrix").
Slots
uplo:Object of class
"character". Must beeither "U", for upper triangular, and "L", for lower triangular.diag:Object of class
"character". Must beeither"U", for unit triangular (diagonal is all ones), or"N"; seetriangularMatrix.p:(only present in
"dtCMatrix":) anintegervector for providing pointers, one for eachcolumn, see the detailed description inCsparseMatrix.i:Object of class
"integer"of length nnzero(number of non-zero elements). These are the row numbers foreach non-zero element in the matrix.j:Object of class
"integer"of length nnzero(number of non-zero elements). These are the column numbers foreach non-zero element in the matrix. (Only present in thedtTMatrixclass.)x:Object of class
"numeric"- the non-zeroelements of the matrix.Dim,Dimnames:The dimension (a length-2
"integer") and corresponding names (orNULL),inherited from theMatrix, see there.
Extends
Class"dgCMatrix", directly.Class"triangularMatrix", directly.Class"dMatrix","sparseMatrix", and more by class"dgCMatrix" etc, see the examples.
Methods
- solve
signature(a = "dtCMatrix", b = "...."):sparse triangular solve (aka “backsolve” or“forwardsolve”), seesolve-methods.- t
signature(x = "dtCMatrix"): returns the transpose ofx- t
signature(x = "dtTMatrix"): returns the transpose ofx
See Also
ClassesdgCMatrix,dgTMatrix,dgeMatrix, anddtrMatrix.
Examples
showClass("dtCMatrix")showClass("dtTMatrix")t1 <- new("dtTMatrix", x= c(3,7), i= 0:1, j=3:2, Dim= as.integer(c(4,4)))t1## from 0-diagonal to unit-diagonal {low-level step}:tu <- t1 ; tu@diag <- "U"tu(cu <- as(tu, "CsparseMatrix"))str(cu)# only two entries in @i and @xstopifnot(cu@i == 1:0, all(2 * symmpart(cu) == Diagonal(4) + forceSymmetric(cu)))t1[1,2:3] <- -1:-2diag(t1) <- 10*c(1:2,3:2)t1 # still triangular(it1 <- solve(t1))t1. <- solve(it1)all(abs(t1 - t1.) < 10 * .Machine$double.eps)## 2nd exampleU5 <- new("dtCMatrix", i= c(1L, 0:3), p=c(0L,0L,0:2, 5L), Dim = c(5L, 5L), x = rep(1, 5), diag = "U")U5(iu <- solve(U5)) # contains one '0'validObject(iu2 <- solve(U5, Diagonal(5)))# failed in earlier versionsI5 <- iu %*% U5 # should equal the identity matrixi5 <- iu2 %*% U5m53 <- matrix(1:15, 5,3, dimnames=list(NULL,letters[1:3]))asDiag <- function(M) as(drop0(M), "diagonalMatrix")stopifnot( all.equal(Diagonal(5), asDiag(I5), tolerance=1e-14) , all.equal(Diagonal(5), asDiag(i5), tolerance=1e-14) , identical(list(NULL, dimnames(m53)[[2]]), dimnames(solve(U5, m53))))Triangular Sparse Compressed Row Matrices
Description
ThedtRMatrix class is a class of triangular, sparsematrices in the compressed, row-oriented format. In thisimplementation the non-zero elements in the rows are sorted intoincreasing columnd order.
Objects from the Class
This class is currently still mostly unimplemented!
Objects can be created by calls of the formnew("dtRMatrix", ...).
Slots
uplo:Object of class
"character". Must beeither "U", for upper triangular, and "L", for lower triangular.At present only the lower triangle form is allowed.diag:Object of class
"character". Must beeither"U", for unit triangular (diagonal is all ones), or"N"; seetriangularMatrix.j:Object of class
"integer"of lengthnnzero(.)(number of non-zero elements). These arethe row numbers for each non-zero element in the matrix.p:Object of class
"integer"of pointers, onefor each row, to the initial (zero-based) index of elements inthe row. (Only present in thedsRMatrixclass.)x:Object of class
"numeric"- the non-zeroelements of the matrix.Dim:The dimension (a length-2
"integer")Dimnames:corresponding names (or
NULL),inherited from theMatrix, see there.
Extends
Class"dgRMatrix", directly.Class"dsparseMatrix", by class"dgRMatrix".Class"dMatrix", by class"dgRMatrix".Class"sparseMatrix", by class"dgRMatrix".Class"Matrix", by class"dgRMatrix".
Methods
No methods currently with class "dsRMatrix" in the signature.
See Also
ClassesdgCMatrix,dgTMatrix,dgeMatrix
Examples
(m0 <- new("dtRMatrix"))(m2 <- new("dtRMatrix", Dim = c(2L,2L), x = c(5, 1:2), p = c(0L,2:3), j= c(0:1,1L)))str(m2)(m3 <- as(Diagonal(2), "RsparseMatrix"))# --> dtRMatrixPacked Triangular Dense Matrices - "dtpMatrix"
Description
The"dtpMatrix" class is the class of triangular,dense, numeric matrices in packed storage. The"dtrMatrix"class is the same except in nonpacked storage.
Objects from the Class
Objects can be created by calls of the formnew("dtpMatrix", ...) or by coercion from other classes of matrices.
Slots
uplo:Object of class
"character". Must beeither "U", for upper triangular, and "L", for lower triangular.diag:Object of class
"character". Must beeither"U", for unit triangular (diagonal is all ones), or"N"; seetriangularMatrix.x:Object of class
"numeric". The numericvalues that constitute the matrix, stored in column-major order.For a packed square matrix of dimensiond \times d,length(x)is of lengthd(d+1)/2(also whendiag == "U"!).Dim,Dimnames:The dimension (a length-2
"integer") and corresponding names (orNULL),inherited from theMatrix, see there.
Extends
Class"ddenseMatrix", directly.Class"triangularMatrix", directly.Class"dMatrix" and more by class"ddenseMatrix" etc, seethe examples.
Methods
- %*%
signature(x = "dtpMatrix", y = "dgeMatrix"):Matrix multiplication; ditto for several other signaturecombinations, seeshowMethods("%*%", class = "dtpMatrix").- determinant
signature(x = "dtpMatrix", logarithm = "logical"):thedeterminant(x)trivially isprod(diag(x)), but computed on log scale to prevent over-and underflow.- diag
signature(x = "dtpMatrix"): ...- norm
signature(x = "dtpMatrix", type = "character"): ...- rcond
signature(x = "dtpMatrix", norm = "character"): ...- solve
signature(a = "dtpMatrix", b = "..."):efficiently using internal backsolve or forwardsolve, seesolve-methods.- t
signature(x = "dtpMatrix"):t(x)remainsa"dtpMatrix", lower triangular ifxis uppertriangular, and vice versa.
See Also
ClassdtrMatrix
Examples
showClass("dtrMatrix")example("dtrMatrix-class", echo=FALSE)(p1 <- pack(T2))str(p1)(pp <- pack(T))ip1 <- solve(p1)stopifnot(length(p1@x) == 3, length(pp@x) == 3, p1 @ uplo == T2 @ uplo, pp @ uplo == T @ uplo, identical(t(pp), p1), identical(t(p1), pp), all((l.d <- p1 - T2) == 0), is(l.d, "dtpMatrix"), all((u.d <- pp - T ) == 0), is(u.d, "dtpMatrix"), l.d@uplo == T2@uplo, u.d@uplo == T@uplo, identical(t(ip1), solve(pp)), is(ip1, "dtpMatrix"), all.equal(as(solve(p1,p1), "diagonalMatrix"), Diagonal(2)))Triangular, dense, numeric matrices
Description
The"dtrMatrix" class is the class of triangular, dense,numeric matrices in nonpacked storage. The"dtpMatrix" classis the same except in packed storage, seepack().
Objects from the Class
Objects can be created by calls of the formnew("dtrMatrix", ...).
Slots
uplo:Object of class
"character". Must beeither "U", for upper triangular, and "L", for lower triangular.diag:Object of class
"character". Must beeither"U", for unit triangular (diagonal is all ones), or"N"; seetriangularMatrix.x:Object of class
"numeric". The numericvalues that constitute the matrix, stored in column-major order.Dim:Object of class
"integer". The dimensionsof the matrix which must be a two-element vector of non-negativeintegers.
Extends
Class"ddenseMatrix", directly.Class"triangularMatrix", directly.Class"Matrix" and others, by class"ddenseMatrix".
Methods
Among others (such as matrix products, e.g.?crossprod-methods),
- norm
signature(x = "dtrMatrix", type = "character"): ..- rcond
signature(x = "dtrMatrix", norm = "character"): ..- solve
signature(a = "dtrMatrix", b = "...."): efficientlyuse a “forwardsolve” orbacksolvefor a lower orupper triangular matrix, respectively, see alsosolve-methods.- +, -, *, ..., ==, >=, ...
all the
Opsgroupmethods are available. When applied to two triangular matrices,these return a triangular matrix when easily possible.
See Also
ClassesddenseMatrix,dtpMatrix,triangularMatrix
Examples
(m <- rbind(2:3, 0:-1))(M <- as(m, "generalMatrix"))(T <- as(M, "triangularMatrix")) # formally upper triangular(T2 <- as(t(M), "triangularMatrix"))stopifnot(T@uplo == "U", T2@uplo == "L", identical(T2, t(T)))m <- matrix(0,4,4); m[upper.tri(m)] <- 1:6(t1 <- Matrix(m+diag(,4)))str(t1p <- pack(t1))(t1pu <- diagN2U(t1p))stopifnot(exprs = { inherits(t1 , "dtrMatrix"); validObject(t1) inherits(t1p, "dtpMatrix"); validObject(t1p) inherits(t1pu,"dtCMatrix"); validObject(t1pu) t1pu@x == 1:6 all(t1pu == t1p) identical((t1pu - t1)@x, numeric())# sparse all-0})Expand Matrix Factorizations
Description
expand1 andexpand2 construct matrix factors fromobjects specifying matrix factorizations. Such objects typicallydo not store the factors explicitly, employing instead a compactrepresentation to save memory.
Usage
expand1(x, which, ...)expand2(x, ...)expand (x, ...)Arguments
x | a matrix factorization, typically inheriting fromvirtual class |
which | a character string indicating a matrix factor. |
... | further arguments passed to or from methods. |
Details
Methods forexpand are retained only for backwardscompatibility withMatrix< 1.6-0. New codeshould useexpand1 andexpand2, whose methodsprovide more control and behave more consistently. Notably,expand2 obeys the rule that the product of the matrixfactors in the returned list should reproduce(within some tolerance) the factorized matrix,including itsdimnames.
Hence ifx is a matrix andy is its factorization,then
all.equal(as(x, "matrix"), as(Reduce(`%*%`, expand2(y)), "matrix"))
should in most cases returnTRUE.
Value
expand1 returns an object inheriting from virtual classMatrix, representing the factor indicatedbywhich, always without row and column names.
expand2 returns a list of factors, typically with namesusing conventional notation, as inlist(L=, U=).The first and last factors get the row and column names of thefactorized matrix, which are preserved in theDimnamesslot ofx.
Methods
The following table lists methods forexpand1 together withallowed values of argumentwhich.
class(x) | which |
Schur | c("Q", "T", "Q.") |
denseLU | c("P1", "P1.", "L", "U") |
sparseLU | c("P1", "P1.", "P2", "P2.", "L", "U") |
sparseQR | c("P1", "P1.", "P2", "P2.", "Q", "Q1", "R", "R1") |
BunchKaufman,pBunchKaufman | c("U", "DU", "U.", "L", "DL", "L.") |
Cholesky,pCholesky | c("P1", "P1.", "L1", "D", "L1.", "L", "L.") |
CHMsimpl,CHMsimpl | c("P1", "P1.", "L1", "D", "L1.", "L", "L.") |
Methods forexpand2 andexpand are describedbelow. Factor names and classes apply also toexpand1.
expand2signature(x = "CHMsimpl"):expands the factorizationA = P_{1}' L_{1} D L_{1}' P_{1} = P_{1}' L L' P_{1}aslist(P1., L1, D, L1., P1)(the default)or aslist(P1., L, L., P1),depending on optional logical argumentLDL.P1andP1.arepMatrix,L1,L1.,L, andL.aredtCMatrix,andDis addiMatrix.expand2signature(x = "CHMsuper"):asCHMsimpl, but the triangular factors arestored asdgCMatrix.expand2signature(x = "p?Cholesky"):expands the factorizationA = L_{1} D L_{1}' = L L'aslist(L1, D, L1.)(the default) or aslist(L, L.),depending on optional logical argumentLDL.L1,L1.,L, andL.aredtrMatrixordtpMatrix,andDis addiMatrix.expand2signature(x = "p?BunchKaufman"):expands the factorizationA = U D_{U} U' = L D_{L} L'whereU = \prod_{k = 1}^{b_{U}} P_{k} U_{k}andL = \prod_{k = 1}^{b_{L}} P_{k} L_{k}aslist(U, DU, U.)orlist(L, DL, L.),depending onx@uplo. If optional argumentcompleteisTRUE, then an unnamed list giving the full expansionwith2 b_{U} + 1or2 b_{L} + 1matrixfactors is returned instead.P_{k}are represented aspMatrix,U_{k}andL_{k}are represented asdtCMatrix, andD_{U}andD_{L}are represented asdsCMatrix.expand2signature(x = "Schur"):expands the factorizationA = Q T Q'aslist(Q, T, Q.).QandQ.arex@Qandt(x@Q)moduloDimnames, andTisx@T.expand2signature(x = "sparseLU"):expands the factorizationA = P_{1}' L U P_{2}'aslist(P1., L, U, P2.).P1.andP2.arepMatrix,andLandUaredtCMatrix.expand2signature(x = "denseLU"):expands the factorizationA = P_{1}' L Uaslist(P1., L, U).P1.is apMatrix,andLandUaredtrMatrixif square anddgeMatrixotherwise.expand2signature(x = "sparseQR"):expands the factorizationA = P_{1}' Q R P_{2}' = P_{1}' Q_{1} R_{1} P_{2}'aslist(P1., Q, R, P2.)orlist(P1., Q1, R1, P2.),depending on optional logical argumentcomplete.P1.andP2.arepMatrix,QandQ1aredgeMatrix,Ris adgCMatrix,andR1is adtCMatrix.expandsignature(x = "CHMfactor"):asexpand2, but returninglist(P, L).expand(x)[["P"]]andexpand2(x)[["P1"]]represent the same permutation matrixP_{1}but have oppositemarginslots and invertedpermslots. The components ofexpand(x)do not preservex@Dimnames.expandsignature(x = "sparseLU"):asexpand2, but returninglist(P, L, U, Q).expand(x)[["Q"]]andexpand2(x)[["P2."]]represent the same permutation matrixP_{2}'but have oppositemarginslots and invertedpermslots.expand(x)[["P"]]representsthe permutation matrixP_{1}rather than itstransposeP_{1}'; it isexpand2(x)[["P1."]]with an invertedpermslot.expand(x)[["L"]]andexpand2(x)[["L"]]represent the same unit lowertriangular matrixL, but withdiagslot equalto"N"and"U", respectively.expand(x)[["L"]]andexpand(x)[["U"]]store thepermuted first and second components ofx@Dimnamesin theirDimnamesslots.expandsignature(x = "denseLU"):asexpand2, but returninglist(L, U, P).expand(x)[["P"]]andexpand2(x)[["P1."]]are identical moduloDimnames. The componentsofexpand(x)do not preservex@Dimnames.
See Also
The virtual classMatrixFactorizationof matrix factorizations.
Generic functionsCholesky,BunchKaufman,Schur,lu, andqr forcomputing factorizations.
Examples
showMethods("expand1", inherited = FALSE)showMethods("expand2", inherited = FALSE)set.seed(0)(A <- Matrix(rnorm(9L, 0, 10), 3L, 3L))(lu.A <- lu(A))(e.lu.A <- expand2(lu.A))stopifnot(exprs = { is.list(e.lu.A) identical(names(e.lu.A), c("P1.", "L", "U")) all(sapply(e.lu.A, is, "Matrix")) all.equal(as(A, "matrix"), as(Reduce(`%*%`, e.lu.A), "matrix"))})## 'expand1' and 'expand2' give equivalent results modulo## dimnames and representation of permutation matrices;## see also function 'alt' in example("Cholesky-methods")(a1 <- sapply(names(e.lu.A), expand1, x = lu.A, simplify = FALSE))all.equal(a1, e.lu.A)## see help("denseLU-class") and others for more examplesMatrix Exponential
Description
Compute the exponential of a matrix.
Usage
expm(x)Arguments
x | a matrix, typically inheriting from the |
Details
The exponential of a matrix is defined as the infinite Taylorseriesexpm(A) = I + A + A^2/2! + A^3/3! + ... (although this isdefinitely not the way to compute it). The method for thedgeMatrix class uses Ward's diagonal Pade' approximation withthree step preconditioning, a recommendation fromMoler & Van Loan (1978) “Nineteen dubious ways...”.
Value
The matrix exponential ofx.
Author(s)
This is a translation of the implementation of the correspondingOctave function contributed to the Octave project byA. Scottedward HodelA.S.Hodel@Eng.Auburn.EDU. A bug in therehas been fixed by Martin Maechler.
References
https://en.wikipedia.org/wiki/Matrix_exponential
Cleve Moler and Charles Van Loan (2003)Nineteen dubious ways to compute the exponential of a matrix,twenty-five years later.SIAM Review45, 1, 3–49.doi:10.1137/S00361445024180
for historical reference mostly:
Moler, C. and Van Loan, C. (1978)Nineteen dubious ways to compute the exponential of a matrix.SIAM Review20, 4, 801–836.doi:10.1137/1020098
Eric W. Weisstein et al. (1999)Matrix Exponential.From MathWorld,https://mathworld.wolfram.com/MatrixExponential.html
See Also
Packageexpm, which provides newer (in some casesfaster, more accurate) algorithms for computing the matrixexponential via its own (non-generic) functionexpm().expm also implementslogm(),sqrtm(), etc.
Generic functionSchur.
Examples
(m1 <- Matrix(c(1,0,1,1), ncol = 2))(e1 <- expm(m1)) ; e <- exp(1)stopifnot(all.equal(e1@x, c(e,0,e,e), tolerance = 1e-15))(m2 <- Matrix(c(-49, -64, 24, 31), ncol = 2))(e2 <- expm(m2))(m3 <- Matrix(cbind(0,rbind(6*diag(3),0))))# sparse!(e3 <- expm(m3)) # upper triangularRead and write external matrix formats
Description
Read matrices stored in the Harwell-Boeing or MatrixMarket formatsor writesparseMatrix objects to one of theseformats.
Usage
readHB(file)readMM(file)writeMM(obj, file, ...)Arguments
obj | a real sparse matrix |
file | for Alternatively, |
... | optional additional arguments. Currently none are used inany methods. |
Value
ThereadHB andreadMM functions return an object thatinherits from the"Matrix" class. Methods for thewriteMM generic functions usually returnNULL and, as a side effect, the matrixobj iswritten tofile in the MatrixMarket format (writeMM).
Note
The Harwell-Boeing format is older and less flexible than theMatrixMarket format. The functionwriteHB was deprecated andhas now been removed. Please usewriteMM instead.
Note that these formats donot know anything aboutdimnames, hence these are dropped bywriteMM().
A very simple way to export small sparse matricesS, is to usesummary(S) which returns adata.frame withcolumnsi,j, and possiblyx, seesummary insparseMatrix-class, and an example below.
References
https://math.nist.gov/MatrixMarket/
Examples
str(pores <- readMM(system.file("external/pores_1.mtx", package = "Matrix")))str(utm <- readHB(system.file("external/utm300.rua" , package = "Matrix")))str(lundA <- readMM(system.file("external/lund_a.mtx" , package = "Matrix")))str(lundA <- readHB(system.file("external/lund_a.rsa" , package = "Matrix")))## https://math.nist.gov/MatrixMarket/data/Harwell-Boeing/counterx/counterx.htmstr(jgl <- readMM(system.file("external/jgl009.mtx" , package = "Matrix")))## NOTE: The following examples take quite some time## ---- even on a fast internet connection:if(FALSE) {## The URL has been corrected, but we need an untar step:u. <- url("https://www.cise.ufl.edu/research/sparse/RB/Boeing/msc00726.tar.gz")str(sm <- readHB(gzcon(u.)))}data(KNex, package = "Matrix")## Store as MatrixMarket (".mtx") file, here inside temporary dir./folder:(MMfile <- file.path(tempdir(), "mmMM.mtx"))writeMM(KNex$mm, file=MMfile)file.info(MMfile)[,c("size", "ctime")] # (some confirmation of the file's)## very simple export - in triplet format - to text file:data(CAex, package = "Matrix")s.CA <- summary(CAex)s.CA # shows (i, j, x) [columns of a data frame]message("writing to ", outf <- tempfile())write.table(s.CA, file = outf, row.names=FALSE)## and read it back -- showing off sparseMatrix():str(dd <- read.table(outf, header=TRUE))## has columns (i, j, x) -> we can use via do.call() as arguments to sparseMatrix():mm <- do.call(sparseMatrix, dd)stopifnot(all.equal(mm, CAex, tolerance=1e-15))Multiplication by Factors from Matrix Factorizations
Description
Multiplies a matrix or vector on the left or right by a factorfrom a matrix factorization or its transpose.
Usage
facmul(x, factor, y, trans = FALSE, left = TRUE, ...)Arguments
x | a |
factor | a character string indicating a factor in thefactorization represented by |
y | a matrix or vector to be multiplied on the left or rightby the factor or its transpose. |
trans | a logical indicating if the transpose of thefactor should be used, rather than the factor itself. |
left | a logical indicating if the |
... | further arguments passed to or from methods. |
Details
facmul is experimental and currently no methods areexported fromMatrix.
Value
The value ofop(M) %*% y ory %*% op(M),depending onleft, whereM is the factor(alwayswithoutdimnames) andop(M)isM ort(M), depending ontrans.
Examples
## Conceptually, methods for 'facmul' _would_ behave as follows ...## Not run: n <- 3Lx <- lu(Matrix(rnorm(n * n), n, n))y <- rnorm(n)L <- unname(expand2(x)[[nm <- "L"]])stopifnot(exprs = { all.equal(facmul(x, nm, y, trans = FALSE, left = TRUE), L %*% y) all.equal(facmul(x, nm, y, trans = FALSE, left = FALSE), y %*% L) all.equal(facmul(x, nm, y, trans = TRUE, left = TRUE), crossprod(L, y)) all.equal(facmul(x, nm, y, trans = TRUE, left = FALSE), tcrossprod(y, L))})## End(Not run)“Low Level” Coercions and Methods
Description
“Semi-API” functions used internally byMatrix,often to bypass S4 dispatch and avoid the associated overhead.These are exported to provide this capability to expert users.Typical users should continue to rely on S4 generic functionsto dispatch suitable methods, by calling,e.g.,as(., <class>) for coercions.
Usage
.M2kind(from, kind = ".", sparse = NA).M2gen(from, kind = ".").M2sym(from, ...).M2tri(from, ...).M2diag(from).M2v(from).M2m(from).M2unpacked(from).M2packed(from).M2C(from).M2R(from).M2T(from).M2V(from).m2V(from, kind = ".").sparse2dense(from, packed = FALSE).diag2dense(from, kind = ".", shape = "t", packed = FALSE, uplo = "U").ind2dense(from, kind = "n").m2dense(from, class = ".ge", uplo = "U", diag = "N", trans = FALSE).dense2sparse(from, repr = "C").diag2sparse(from, kind = ".", shape = "t", repr = "C", uplo = "U").ind2sparse(from, kind = "n", repr = ".").m2sparse(from, class = ".gC", uplo = "U", diag = "N", trans = FALSE).tCRT(x, lazy = TRUE).diag.dsC(x, Chx = Cholesky(x, LDL = TRUE), res.kind = "diag").solve.dgC.lu (a, b, tol = .Machine$double.eps, check = TRUE).solve.dgC.qr (a, b, order = 3L, check = TRUE).solve.dgC.chol(a, b, check = TRUE).updateCHMfactor(object, parent, mult = 0)Arguments
from,x,a,b | a |
kind | a string ( |
shape | a string ( |
repr | a string ( |
packed | a logical indicating if the result shouldinherit from |
sparse | a logical indicating if the result should inheritfrom |
uplo | a string ( |
diag | a string ( |
trans | a logical indicating if the result should be a 1-rowmatrix rather than a 1-column matrix where |
class | a string whose first three characters specify the classof the result. It should match the pattern |
... | optional arguments passed to |
lazy | a logical indicating if the transpose should beconstructed with minimal allocation, but possiblywithoutpreserving representation. |
Chx | optionally, the |
res.kind | a string in |
tol | see |
order | see |
check | a logical indicating if the first argument should betested for inheritance from |
object | a Cholesky factorization inheriting from virtual class |
parent | |
mult | a numeric vector of postive length. Only the firstelement is used, and that must be finite. |
Details
Functions with names of the form.<A>2<B> implement coercionsfrom virtual class A to the “nearest” non-virtual subclass ofvirtual class B, where the virtual classes are abbreviated as follows:
MVmmatrix
vvector
denseunpackedpackedsparseCRTgensymtridiagind
Abbreviations should be seen as a guide, rather than as anexact description of behaviour. Notably,.m2dense,.m2sparse, and.m2V accept vectors that arenot matrices.
.tCRT(x)
Iflazy = TRUE, then.tCRT constructs the transposeofx using the most efficient representation,which for ‘CRT’ is ‘RCT’. Iflazy = FALSE,then.tCRT preserves the representation ofx,behaving as the corresponding methods for generic functiont.
.diag.dsC(x)
.diag.dsC computes (or uses ifChx is supplied)the Cholesky factorization ofx asL D L' in orderto calculate one of several possible statistics from the diagonalentries ofD. Seeres.kind under ‘Arguments’.
.solve.dgC.*(a, b)
.solve.dgC.lu(a, b) needs a square matrixa..solve.dgC.qr(a, b) needs a “long” matrixa,withnrow(a) >= ncol(a)..solve.dgC.chol(a, b) needs a “wide” matrixa,withnrow(a) <= ncol(a).
All three may be used to solve sparse linear systems directly.Only.solve.dgC.qr and.solve.dgC.chol be usedto solve sparseleast squares problems.
.updateCHMfactor(object, parent, mult)
.updateCHMfactor updatesobject with the resultof Cholesky factorizingF(parent) + mult[1] * diag(nrow(parent)),i.e.,F(parent) plusmult[1] times the identity matrix,whereF = identity ifparent is adsCMatrixandF = tcrossprod ifparent is adgCMatrix.The nonzero pattern ofF(parent) must matchthat ofS ifobject = Cholesky(S, ...).
Examples
D. <- diag(x = c(1, 1, 2, 3, 5, 8))D.0 <- Diagonal(x = c(0, 0, 0, 3, 5, 8))S. <- toeplitz(as.double(1:6))C. <- new("dgCMatrix", Dim = c(3L, 4L), p = c(0L, 1L, 1L, 1L, 3L), i = c(1L, 0L, 2L), x = c(-8, 2, 3))stopifnot(exprs = { identical(.M2tri (D.), as(D., "triangularMatrix")) identical(.M2sym (D.), as(D., "symmetricMatrix")) identical(.M2diag(D.), as(D., "diagonalMatrix")) identical(.M2kind(C., "l"), as(C., "lMatrix")) identical(.M2kind(.sparse2dense(C.), "l"), as(as(C., "denseMatrix"), "lMatrix")) identical(.diag2sparse(D.0, ".", "t", "C"), .dense2sparse(.diag2dense(D.0, ".", "t", TRUE), "C")) identical(.M2gen(.diag2dense(D.0, ".", "s", FALSE)), .sparse2dense(.M2gen(.diag2sparse(D.0, ".", "s", "T")))) identical(S., .M2m(.m2sparse(S., ".sR"))) identical(S. * lower.tri(S.) + diag(1, 6L), .M2m(.m2dense (S., ".tr", "L", "U"))) identical(.M2R(C.), .M2R(.M2T(C.))) identical(.tCRT(C.), .M2R(t(C.)))})A <- tcrossprod(C.)/6 + Diagonal(3, 1/3); A[1,2] <- 3; Astopifnot(exprs = { is.numeric( x. <- c(2.2, 0, -1.2) ) all.equal(x., .solve.dgC.lu(A, c(1,0,0), check=FALSE)) all.equal(x., .solve.dgC.qr(A, c(1,0,0), check=FALSE))})## Solving sparse least squares:X <- rbind(A, Diagonal(3)) # design matrix X (for L.S.)Xt <- t(X) # *transposed* X (for L.S.)(y <- drop(crossprod(Xt, 1:3)) + c(-1,1)/1000) # small rand.err.str(solveCh <- .solve.dgC.chol(Xt, y, check=FALSE)) # Xt *is* dgC..stopifnot(exprs = { all.equal(solveCh$coef, 1:3, tol = 1e-3)# rel.err ~ 1e-4 all.equal(solveCh$coef, drop(solve(tcrossprod(Xt), Xt %*% y))) all.equal(solveCh$coef, .solve.dgC.qr(X, y, check=FALSE))})Force a Matrix to 'symmetricMatrix' Without Symmetry Checks
Description
Force a square matrixx to asymmetricMatrix,without a symmetry check as it would be applied foras(x, "symmetricMatrix").
Usage
forceSymmetric(x, uplo)Arguments
x | any square matrix (of numbers), either “"traditional"”( |
uplo | optional string, |
Value
a square matrix inheriting from classsymmetricMatrix.
See Also
symmpart for the symmetric part of a matrix, orthe coercionsas(x, <symmetricMatrix class>).
Examples
## Hilbert matrix i <- 1:6 h6 <- 1/outer(i - 1L, i, "+") sd <- sqrt(diag(h6)) hh <- t(h6/sd)/sd # theoretically symmetric isSymmetric(hh, tol=0) # FALSE; hence try( as(hh, "symmetricMatrix") ) # fails, but this works fine: H6 <- forceSymmetric(hh) ## result can be pretty surprising: (M <- Matrix(1:36, 6)) forceSymmetric(M) # symmetric, hence very different in lower triangle (tm <- tril(M)) forceSymmetric(tm)Formatting Sparse Numeric Matrices Utilities
Description
Utilities for formatting sparse numeric matrices in a flexible way.These functions are used by theformat andprintmethods for sparse matrices and can be applied as well to standardRmatrices. Note thatall arguments but the first are optional.
formatSparseM() is the main “workhorse” offormatSpMatrix, theformat method for sparsematrices.
.formatSparseSimple() is a simple helper function, also dealingwith (short/empty) column names construction.
Usage
formatSparseM(x, zero.print = ".", align = c("fancy", "right"), m = as(x,"matrix"), asLogical=NULL, uniDiag=NULL, digits=NULL, cx, iN0, dn = dimnames(m)).formatSparseSimple(m, asLogical=FALSE, digits=NULL, col.names, note.dropping.colnames = TRUE, dn=dimnames(m))Arguments
x | anR object inheriting from class |
zero.print | character which should be used forstructural zeroes. The default |
align | a string specifying how the |
m | (optional) a (standardR) |
asLogical | should the matrix be formatted as a logical matrix(or rather as a numeric one); mostly for |
uniDiag | logical indicating if the diagonal entries of a sparseunit triangular or unit-diagonal matrix should be formatted as |
digits | significant digits to use for printing, see |
cx | (optional) character matrix; a formatted version of |
iN0 | (optional) integer vector, specifying the location of thenon-zeroes of |
col.names,note.dropping.colnames | see |
dn |
|
Value
a character matrix likecx, where the zeros have been replacedwith (padded versions of)zero.print.As this is adense matrix, do not use these functions forreally large (really) sparse matrices!
Author(s)
Martin Maechler
See Also
formatSpMatrix which callsformatSparseM() and istheformat method for sparse matrices.printSpMatrix which is used by the (typicallyimplicitly called)show andprint methodsfor sparse matrices.
Examples
m <- suppressWarnings(matrix(c(0, 3.2, 0,0, 11,0,0,0,0,-7,0), 4,9))fm <- formatSparseM(m)noquote(fm)## nice, but this is nicer {with "units" vertically aligned}:print(fm, quote=FALSE, right=TRUE)## and "the same" as :Matrix(m)## align = "right" is cheaper --> the "." are not aligned:noquote(f2 <- formatSparseM(m,align="r"))stopifnot(f2 == fm | m == 0, dim(f2) == dim(m), (f2 == ".") == (m == 0))Class "generalMatrix" of General Matrices
Description
Virtual class of “general” matrices; i.e., matricesthat do not have a known property such as symmetric, triangular, ordiagonal.
Objects from the Class
A virtual Class: No objects may be created from it.
Slots
Dim, Dimnamesinherited from virtual class
Matrix.factorsa list of
MatrixFactorizationobjects cachingfactorizations of the matrix. Typically, it is initializedas an empty list and updated “automagically” whenevera factorization is computed.
Extends
Class"Matrix", directly.
See Also
Virtual classessymmetricMatrix,triangularMatrix, anddiagonalMatrix.
Methods for image() in Package 'Matrix'
Description
Methods for functionimage in packageMatrix. An image of a matrix simply color codes all matrixentries and draws then\times m matrix using ann\times m grid of (colored) rectangles.
TheMatrix packageimage methods are based onlevelplot() from packagelattice; hencethese methods return an “object” of class"trellis",producing a graphic when (auto-)print()ed.
Usage
## S4 method for signature 'dgTMatrix'image(x, xlim = c(1, di[2]), ylim = c(di[1], 1), aspect = "iso", sub = sprintf("Dimensions: %d x %d", di[1], di[2]), xlab = "Column", ylab = "Row", cuts = 15, useRaster = FALSE, useAbs = NULL, colorkey = !useAbs, col.regions = NULL, lwd = NULL, border.col = NULL, ...)Arguments
x | a Matrix object, i.e., fulfilling |
xlim,ylim | x- and y-axis limits; may be used to “zoominto” matrix. Note that |
aspect | aspect ratio specified as number (y/x) or string;see |
sub,xlab,ylab | axis annotation with sensible defaults;see |
cuts | number of levels the range of matrix values would bedivided into. |
useRaster | logical indicating if raster graphics should be used(instead of the tradition rectangle vector drawing). If true, Note that using raster graphics may often be faster, but can be slower,depending on the matrix dimensions and the graphics device (dimensions). |
useAbs | logical indicating if |
colorkey | logical indicating if a color key aka ‘legend’should be produced. Default is to draw one, unless |
col.regions | vector of gradually varying colors; see |
lwd | (only used when |
border.col | color for the border of each rectangle. |
... | further arguments passed to methods and |
Value
as alllattice graphics functions,image(<Matrix>)returns a"trellis" object, effectively the result oflevelplot().
Methods
All methods currently end up calling the method for thedgTMatrix class.UseshowMethods(image) to list them all.
See Also
levelplot, andprint.trellis from packagelattice.
Examples
showMethods(image)## And if you want to see the method definitions:showMethods(image, includeDefs = TRUE, inherited = FALSE)data(CAex, package = "Matrix")image(CAex, main = "image(CAex)") -> imgC; imgCstopifnot(!is.null(leg <- imgC$legend), is.list(leg$right)) # failed for 2 days ..image(CAex, useAbs=TRUE, main = "image(CAex, useAbs=TRUE)")cCA <- Cholesky(crossprod(CAex), Imult = .01)## See ?print.trellis --- place two image() plots side by side:print(image(cCA, main="Cholesky(crossprod(CAex), Imult = .01)"), split=c(x=1,y=1,nx=2, ny=1), more=TRUE)print(image(cCA, useAbs=TRUE), split=c(x=2,y=1,nx=2,ny=1))data(USCounties, package = "Matrix")image(USCounties)# hugeimage(sign(USCounties))## just the pattern # how the result looks, may depend heavily on # the device, screen resolution, antialiasing etc # e.g. x11(type="Xlib") may show very differently than cairo-based## Drawing borders around each rectangle; # again, viewing depends very much on the device:image(USCounties[1:400,1:200], lwd=.1)## Using (xlim,ylim) has advantage : matrix dimension and (col/row) indices:image(USCounties, c(1,200), c(1,400), lwd=.1)image(USCounties, c(1,300), c(1,200), lwd=.5 )image(USCounties, c(1,300), c(1,200), lwd=.01)## These 3 are all equivalent :(I1 <- image(USCounties, c(1,100), c(1,100), useAbs=FALSE)) I2 <- image(USCounties, c(1,100), c(1,100), useAbs=FALSE, border.col=NA) I3 <- image(USCounties, c(1,100), c(1,100), useAbs=FALSE, lwd=2, border.col=NA)stopifnot(all.equal(I1, I2, check.environment=FALSE), all.equal(I2, I3, check.environment=FALSE))## using an opaque border colorimage(USCounties, c(1,100), c(1,100), useAbs=FALSE, lwd=3, border.col = adjustcolor("skyblue", 1/2))if(interactive() || nzchar(Sys.getenv("R_MATRIX_CHECK_EXTRA"))) {## Using raster graphics: For PDF this would give a 77 MB file,## however, for such a large matrix, this is typically considerably## *slower* (than vector graphics rectangles) in most cases :if(doPNG <- !dev.interactive()) png("image-USCounties-raster.png", width=3200, height=3200)image(USCounties, useRaster = TRUE) # should not suffer from anti-aliasingif(doPNG) dev.off() ## and now look at the *.png image in a viewer you can easily zoom in and out}#only if(doExtras)Index Matrices
Description
TheindMatrix class is the class of row and columnindex matrices, stored as 1-based integer index vectors.A row (column) index matrix is a matrix whose rows (columns)are standard unit vectors. Such matrices are usefulwhen mapping observations to discrete sets of covariate values.
Multiplying a matrix on the left by a row index matrix isequivalent to indexing its rows, i.e., sampling the rows“with replacement”. Analogously, multiplying a matrixon the right by a column index matrix is equivalent toindexing its columns. Indeed, such products are implemented inMatrix as indexing operations; see ‘Details’ below.
A matrix whose rowsand columns are standard unit vectorsis called apermutation matrix. This special case isdesignated by thepMatrix class, a directsubclass ofindMatrix.
Details
The transpose of an index matrix is an index matrix with identicalperm but oppositemargin. Hence the transpose of arow index matrix is a column index matrix, and vice versa.
The cross product of a row index matrixR and itself is adiagonal matrix whose diagonal entries are the the number of entriesin each column ofR.
Given a row index matrixR withperm slotp,a column index matrixC withperm slotq,and a matrixM with conformable dimensions, we have
R M | = | R %*% M | = | M[p, ] |
M C | = | M %*% C | = | M[, q] |
C'M | = | crossprod(C, M) | = | M[q, ] |
MR' | = | tcrossprod(M, R) | = | M[, p] |
R'R | = | crossprod(R) | = | Diagonal(x=tabulate(p, ncol(R))) |
CC' | = | tcrossprod(C) | = | Diagonal(x=tabulate(q, nrow(C))) |
Operations on index matrices that result in index matrices willaccordingly return anindMatrix. These include productsof two column index matrices and (equivalently) column-indexingof a column index matrix (when dimensions are not dropped).Most other operations onindMatrix treat them as sparsenonzero pattern matrices (i.e., inheriting from virtual classnsparseMatrix). Hence vector-valued subsetsofindMatrix, such as those given bydiag,are always of type"logical".
Objects from the Class
Objects can be created explicitly with calls of the formnew("indMatrix", ...), but they are more commonly createdby coercing 1-based integer index vectors, with calls of theformas(., "indMatrix"); see ‘Methods’ below.
Slots
marginan integer, either 1 or 2, specifyingwhether the matrix is a row (1) or column (2) index.
perma 1-based integer index vector, i.e.,a vector of length
Dim[margin]with elementstaken from1:Dim[1+margin%%2].Dim,Dimnamesinherited from virtualsuperclass
Matrix.
Extends
Classes"sparseMatrix" and"generalMatrix", directly.
Methods
%*%signature(x = "indMatrix", y = "Matrix")and others listed byshowMethods("%*%", classes = "indMatrix"):matrix products implemented where appropriate as indexing operations.coercesignature(from = "numeric", to = "indMatrix"):supporting typicalindMatrixconstruction froma vector of positive integers. Row indexing is assumed.coercesignature(from = "list", to = "indMatrix"):supportingindMatrixconstruction for rowandcolumn indexing, including index vectors of length 0 andindex vectors whose maximum is less than the number of rowsor columns being indexed.coercesignature(from = "indMatrix", to = "matrix"):coercion to a traditionalmatrixoflogical type,withFALSEandTRUEin place of 0 and 1.tsignature(x = "indMatrix"):the transpose, which is anindMatrixwith identicalpermbut oppositemargin.rowSums,rowMeans,colSums,colMeanssignature(x = "indMatrix"):row and column sums and means.rbind2,cbind2signature(x = "indMatrix", y = "indMatrix"):row-wise catenation of two row index matrices with equal numbersof columns and column-wise catenation of two column index matriceswith equal numbers of rows.- kronecker
signature(X = "indMatrix", Y = "indMatrix"):Kronecker product of two row index matrices or two column indexmatrices, giving the row or column index matrix corresponding totheir “interaction”.
Author(s)
Fabian Scheipl at ‘uni-muenchen.de’, building on the existing classpMatrix after a nice hike's conversation withMartin Maechler. Methods forcrossprod(x, y) andkronecker(x, y) with both arguments inheriting fromindMatrix were made considerably faster thanks to a suggestionby Boris Vaillant. Diverse tweaks by Martin Maechler andMikael Jagan, notably the latter's implementation ofmargin,prior to which theindMatrix class was designated only forrow index matrices.
See Also
SubclasspMatrix of permutation matrices,a special case of index matrices; virtual classnMatrix of nonzero pattern matrices,and its subclasses.
Examples
p1 <- as(c(2,3,1), "pMatrix")(sm1 <- as(rep(c(2,3,1), e=3), "indMatrix"))stopifnot(all(sm1 == p1[rep(1:3, each=3),]))## row-indexing of a <pMatrix> turns it into an <indMatrix>:class(p1[rep(1:3, each=3),])set.seed(12) # so we know '10' is in sample## random index matrix for 30 observations and 10 unique values:(s10 <- as(sample(10, 30, replace=TRUE),"indMatrix"))## Sample rows of a numeric matrix :(mm <- matrix(1:10, nrow=10, ncol=3))s10 %*% mmset.seed(27)IM1 <- as(sample(1:20, 100, replace=TRUE), "indMatrix")IM2 <- as(sample(1:18, 100, replace=TRUE), "indMatrix")(c12 <- crossprod(IM1,IM2))## same as cross-tabulation of the two index vectors:stopifnot(all(c12 - unclass(table(IM1@perm, IM2@perm)) == 0))# 3 observations, 4 implied values, first does not occur in sample:as(2:4, "indMatrix")# 3 observations, 5 values, first and last do not occur in sample:as(list(2:4, 5), "indMatrix")as(sm1, "nMatrix")s10[1:7, 1:4] # gives an "ngTMatrix" (most economic!)s10[1:4, ] # preserves "indMatrix"-classI1 <- as(c(5:1,6:4,7:3), "indMatrix")I2 <- as(7:1, "pMatrix")(I12 <- rbind(I1, I2))stopifnot(is(I12, "indMatrix"), identical(I12, rbind(I1, I2)), colSums(I12) == c(2L,2:4,4:2))Virtual Class “index” of Index Vectors
Description
Classindex is a virtual class designating index vectors,or “subscripts”, for (possibly named) vectors and arrays.It is typically used in signatures of methods for the subscriptand subassignment operators, namely[ and[<-.It is implemented as aunion of the atomic vector classesnumeric,logical,andcharacter.
See Also
[,[-methods, and[<–methods.
Examples
showClass("index")Utilities for Permutation Vectors
Description
invertPerm andsignPerm compute the inverse and signof a length-n permutation vector.isPerm testsif a length-n integer vector is a valid permutation vector.asPerm coerces a length-m transposition vector to alength-n permutation vector, wherem <= n.
Usage
invertPerm(p, off = 1L, ioff = 1L)signPerm(p, off = 1L)isPerm(p, off = 1L)asPerm(pivot, off = 1L, ioff = 1L, n = length(pivot))invPerm(p, zero.p = FALSE, zero.res = FALSE)Arguments
p | an integer vector of length |
pivot | an integer vector of length |
off | an integer offset, indicating that |
ioff | an integer offset, indicating that the resultshould be a permutation of |
n | a integer greater than or equal to |
zero.p | a logical. Equivalent to |
zero.res | a logical. Equivalent to |
Details
invertPerm(p, off, ioff=1) is equivalent toorder(p) orsort.list(p)for all values ofoff. For the default valueoff=1, it returns the value ofp afterp[p] <- seq_along(p).
invPerm is a simple wrapper aroundinvertPerm,retained for backwards compatibility.
Value
By default, i.e., withoff=1 andioff=1:
invertPerm(p) returns an integer vector of lengthlength(p) such thatp[invertPerm(p)]andinvertPerm(p)[p] are bothseq_along(p),i.e., the identity permutation.
signPerm(p) returns 1 ifp is an even permutationand-1 otherwise (i.e., ifp is odd).
isPerm(p) returnsTRUE ifp is apermutation ofseq_along(p) andFALSE otherwise.
asPerm(pivot) returns the result of transposing elementsi andpivot[i] of a permutation vector initializedasseq_len(n), fori inseq_along(pivot).
See Also
ClasspMatrix of permutation matrices.
Examples
p <- sample(10L) # a random permutation vectorip <- invertPerm(p)s <- signPerm(p)## 'p' and 'ip' are indeed inverses:stopifnot(exprs = { isPerm(p) isPerm(ip) identical(s, 1L) || identical(s, -1L) identical(s, signPerm(ip)) identical(p[ip], 1:10) identical(ip[p], 1:10) identical(invertPerm(ip), p)})## Product of transpositions (1 2)(2 1)(4 3)(6 8)(10 1) = (3 4)(6 8)(1 10)pivot <- c(2L, 1L, 3L, 3L, 5L, 8L, 7L, 8L, 9L, 1L)q <- asPerm(pivot)stopifnot(exprs = { identical(q, c(10L, 2L, 4L, 3L, 5L, 8L, 7L, 6L, 9L, 1L)) identical(q[q], seq_len(10L)) # because the permutation is odd: signPerm(q) == -1L})invPerm # a less general version of 'invertPerm'is.na(), is.finite() Methods for 'Matrix' Objects
Description
Methods for generic functionsanyNA(),is.na(),is.nan(),is.infinite(), andis.finite(),for objects inheriting from virtual classMatrix orsparseVector.
Usage
## S4 method for signature 'denseMatrix'is.na(x)## S4 method for signature 'sparseMatrix'is.na(x)## S4 method for signature 'diagonalMatrix'is.na(x)## S4 method for signature 'indMatrix'is.na(x)## S4 method for signature 'sparseVector'is.na(x)## ...## and likewise for anyNA, is.nan, is.infinite, is.finiteArguments
x | anR object, here a sparse or dense matrix or vector. |
Value
Foris.*(), annMatrix ornsparseVector matching the dimensionsofx and specifying the positions inx of(some subset of)NA,NaN,Inf, and-Inf.ForanyNA(),TRUE ifx containsNAorNaN andFALSE otherwise.
See Also
Examples
(M <- Matrix(1:6, nrow = 4, ncol = 3, dimnames = list(letters[1:4], LETTERS[1:3])))stopifnot(!anyNA(M), !any(is.na(M)))M[2:3, 2] <- NA(inM <- is.na(M))stopifnot(anyNA(M), sum(inM) == 2)(A <- spMatrix(nrow = 10, ncol = 20, i = c(1, 3:8), j = c(2, 9, 6:10), x = 7 * (1:7)))stopifnot(!anyNA(A), !any(is.na(A)))A[2, 3] <- A[1, 2] <- A[5, 5:9] <- NA(inA <- is.na(A))stopifnot(anyNA(A), sum(inA) == 1 + 1 + 5)Are the Dimnamesdn NULL-like ?
Description
is.null.DN(dn) is less strict thanis.null(dn),because it is also true (TRUE) when the dimnamesdn are “like”NULL, orlist(NULL,NULL), asthey can easily be for the traditionalR matrices(matrix) which have no formalclassdefinition, and hence much freedom in how theirdimnameslook like.
Usage
is.null.DN(dn)Arguments
dn |
Value
Note
This function is really to be used on “traditional” matricesrather than those inheriting fromMatrix, asthe latter will always have dimnameslist(NULL,NULL) exactly,in such a case.
Author(s)
Martin Maechler
See Also
Examples
m1 <- m2 <- m3 <- m4 <- m <- matrix(round(100 * rnorm(6)), 2, 3)dimnames(m1) <- list(NULL, NULL)dimnames(m2) <- list(NULL, character())dimnames(m3) <- rev(dimnames(m2))dimnames(m4) <- rep(list(character()),2)m4 # prints absolutely identically to mc.o <- capture.outputcm <- c.o(m)stopifnot(exprs = { m == m1; m == m2; m == m3; m == m4identical(cm, c.o(m1));identical(cm, c.o(m2))identical(cm, c.o(m3)); identical(cm, c.o(m4))})hasNoDimnames <- function(.) is.null.DN(dimnames(.))stopifnot(exprs = { hasNoDimnames(m) hasNoDimnames(m1); hasNoDimnames(m2) hasNoDimnames(m3); hasNoDimnames(m4) hasNoDimnames(Matrix(m) -> M) hasNoDimnames(as(M, "sparseMatrix"))})Methods for Function 'isSymmetric' in Package 'Matrix'
Description
isSymmetric tests whether its argument is a symmetric squarematrix, by default tolerating some numerical fuzz and requiringsymmetric[dD]imnames in addition to symmetry in themathematical sense.isSymmetric is a generic function inbase, which has amethod for traditionalmatrices of implicitclass"matrix".Methods are defined here for various proper and virtual classesinMatrix, so thatisSymmetric works for all objectsinheriting from virtual class"Matrix".
Usage
## S4 method for signature 'denseMatrix'isSymmetric(object, checkDN = TRUE, ...)## S4 method for signature 'CsparseMatrix'isSymmetric(object, checkDN = TRUE, ...)## S4 method for signature 'RsparseMatrix'isSymmetric(object, checkDN = TRUE, ...)## S4 method for signature 'TsparseMatrix'isSymmetric(object, checkDN = TRUE, ...)## S4 method for signature 'diagonalMatrix'isSymmetric(object, checkDN = TRUE, ...)## S4 method for signature 'indMatrix'isSymmetric(object, checkDN = TRUE, ...)## S4 method for signature 'dgeMatrix'isSymmetric(object, checkDN = TRUE, tol = 100 * .Machine$double.eps, tol1 = 8 * tol, ...)## S4 method for signature 'dgCMatrix'isSymmetric(object, checkDN = TRUE, tol = 100 * .Machine$double.eps, ...)Arguments
object | a |
checkDN | alogical indicating whether symmetry of the |
tol,tol1 | numerical tolerances allowingapproximatesymmetry of numeric (rather than logical) matrices. See also |
... | further arguments passed to methods(typically methods for |
Details
TheDimnamesslot ofobject, saydn,is considered to be symmetric if and only if
dn[[1]]anddn[[2]]are identicalorone isNULL;andndn <- names(dn)isNULLorndn[1]andndn[2]are identicalorone is the empty string"".
Hencelist(a=nms, a=nms) is considered to besymmetric,and so too arelist(a=nms, NULL) andlist(NULL, a=nms).
Note that this definition islooser than that employed byisSymmetric.matrix, which requiresdn[1] anddn[2] to be identical, wheredn is thedimnamesattribute of a traditional matrix.
Value
Alogical, eitherTRUE orFALSE(neverNA).
See Also
forceSymmetric;symmpart andskewpart;virtual class"symmetricMatrix" and its subclasses.
Examples
isSymmetric(Diagonal(4)) # TRUE of courseM <- Matrix(c(1,2,2,1), 2,2)isSymmetric(M) # TRUE (*and* of formal class "dsyMatrix")isSymmetric(as(M, "generalMatrix")) # still symmetric, even if not "formally"isSymmetric(triu(M)) # FALSE## Look at implementations:showMethods("isSymmetric", includeDefs = TRUE) # includes S3 generic from baseTest whether a Matrix is Triangular or Diagonal
Description
isTriangular andisDiagonal test whether their argumentis a triangular or diagonal matrix, respectively. Unlike the analogousisSymmetric, these two functions are genericallyfromMatrix rather thanbase. HenceMatrixdefines methods for traditional matrices of implicitclass"matrix" in addition to matrices inheriting fromvirtual class"Matrix".
By our definition, triangular and diagonal matrices aresquare,i.e., they have the same number of rows and columns.
Usage
isTriangular(object, upper = NA, ...)isDiagonal(object)Arguments
object | anR object, typically a matrix. |
upper | alogical, either |
... | further arguments passed to methods(currently unused byMatrix). |
Value
Alogical, eitherTRUE orFALSE(neverNA).
Ifobject is triangular andupper isNA, thenisTriangular returnsTRUE with anattributekind, either"U" or"L", indicating thatobject isupper orlower triangular, respectively. Users should not rely on howkind is determined for diagonalmatrices, which are both upper and lower triangular.
See Also
isSymmetric;virtual classes"triangularMatrix" and"diagonalMatrix" and their subclasses.
Examples
isTriangular(Diagonal(4))## is TRUE: a diagonal matrix is also (both upper and lower) triangular(M <- Matrix(c(1,2,0,1), 2,2))isTriangular(M) # TRUE (*and* of formal class "dtrMatrix")isTriangular(as(M, "generalMatrix")) # still triangular, even if not "formally"isTriangular(crossprod(M)) # FALSEisDiagonal(matrix(c(2,0,0,1), 2,2)) # TRUE## Look at implementations:showMethods("isTriangular", includeDefs = TRUE)showMethods("isDiagonal", includeDefs = TRUE)Methods for Function 'kronecker()' in Package 'Matrix'
Description
Computes Kronecker products for objects inheriting from"Matrix".
In order to preserver sparseness, we treat0 * NA as0,not asNA as usually inR (and as used for thebase functionkronecker).
Methods
- kronecker
signature(X = "Matrix", Y = "ANY").......- kronecker
signature(X = "ANY", Y = "Matrix").......- kronecker
signature(X = "diagonalMatrix", Y = "ANY").......- kronecker
signature(X = "sparseMatrix", Y = "ANY").......- kronecker
signature(X = "TsparseMatrix", Y = "TsparseMatrix").......- kronecker
signature(X = "dgTMatrix", Y = "dgTMatrix").......- kronecker
signature(X = "dtTMatrix", Y = "dtTMatrix").......- kronecker
signature(X = "indMatrix", Y = "indMatrix").......
Examples
(t1 <- spMatrix(5,4, x= c(3,2,-7,11), i= 1:4, j=4:1)) # 5 x 4(t2 <- kronecker(Diagonal(3, 2:4), t1)) # 15 x 12## should also work with special-cased logical matricesl3 <- upper.tri(matrix(,3,3))M <- Matrix(l3)(N <- as(M, "nsparseMatrix")) # "ntCMatrix" (upper triangular)N2 <- as(N, "generalMatrix") # (lost "t"riangularity)MM <- kronecker(M,M)NN <- kronecker(N,N) # "dtTMatrix" i.e. did keepNN2 <- kronecker(N2,N2)stopifnot(identical(NN,MM), is(NN2, "sparseMatrix"), all(NN2 == NN), is(NN, "triangularMatrix"))Virtual Class "ldenseMatrix" of Dense Logical Matrices
Description
ldenseMatrix is the virtual class of all denselogical(S4) matrices. It extends bothdenseMatrixandlMatrix directly.
Slots
x:logical vector containing the entries of the matrix.
Dim,Dimnames:see
Matrix.
Extends
Class"lMatrix", directly.Class"denseMatrix", directly.Class"Matrix", by class"lMatrix".Class"Matrix", by class"denseMatrix".
Methods
- as.vector
signature(x = "ldenseMatrix", mode = "missing"): ...- which
signature(x = "ndenseMatrix"), semanticallyequivalent tobase functionwhich(x, arr.ind);for details, see thelMatrixclass documentation.
See Also
ClasslgeMatrix and the other subclasses.
Examples
showClass("ldenseMatrix")as(diag(3) > 0, "ldenseMatrix")Class "ldiMatrix" of Diagonal Logical Matrices
Description
The class"ldiMatrix" of logical diagonal matrices.
Objects from the Class
Objects can be created by calls of the formnew("ldiMatrix", ...)but typically rather viaDiagonal.
Slots
x:"logical"vector.diag:"character"string, either "U" or "N",seeddiMatrix.Dim,Dimnames:matrix dimension and
dimnames, see theMatrixclassdescription.
Extends
Class"diagonalMatrix" andclass"lMatrix", directly.
Class"sparseMatrix", by class"diagonalMatrix".
See Also
ClassesddiMatrix anddiagonalMatrix; functionDiagonal.
Examples
(lM <- Diagonal(x = c(TRUE,FALSE,FALSE)))str(lM)#> gory details (slots)crossprod(lM) # numeric(nM <- as(lM, "nMatrix"))crossprod(nM) # pattern sparseClass "lgeMatrix" of General Dense Logical Matrices
Description
This is the class of general denselogicalmatrices.
Slots
x:Object of class
"logical". The logicalvalues that constitute the matrix, stored in column-major order.Dim,Dimnames:The dimension (a length-2
"integer") and corresponding names (orNULL), see theMatrixclass.factors:Object of class
"list". A namedlist of factorizations that have been computed for the matrix.
Extends
Class"ldenseMatrix", directly.Class"lMatrix", by class"ldenseMatrix".Class"denseMatrix", by class"ldenseMatrix".Class"Matrix", by class"ldenseMatrix".Class"Matrix", by class"ldenseMatrix".
Methods
Currently, mainlyt() and coercion methods (foras(.)); use, e.g.,showMethods(class="lgeMatrix") for details.
See Also
Non-general logical dense matrix classes such asltrMatrix, orlsyMatrix;sparse logical classes such aslgCMatrix.
Examples
showClass("lgeMatrix")str(new("lgeMatrix"))set.seed(1)(lM <- Matrix(matrix(rnorm(28), 4,7) > 0))# a simple random lgeMatrixset.seed(11)(lC <- Matrix(matrix(rnorm(28), 4,7) > 0))# a simple random lgCMatrixas(lM, "CsparseMatrix")Sparse logical matrices
Description
ThelsparseMatrix class is a virtual classof logical sparse matrices, i.e., sparse matrices with entriesTRUE,FALSE, orNA.
These can be stored in the “triplet” form (classTsparseMatrix, subclasseslgTMatrix,lsTMatrix, andltTMatrix) or in compressedcolumn-oriented form (classCsparseMatrix,subclasseslgCMatrix,lsCMatrix, andltCMatrix)or–rarely–in compressed row-oriented form (classRsparseMatrix, subclasseslgRMatrix,lsRMatrix, andltRMatrix). The second letter in thename of these non-virtual classes indicatesgeneral,symmetric, ortriangular.
Details
Note that triplet stored (TsparseMatrix) matricessuch aslgTMatrix may contain duplicated pairs of indices(i,j) as for the corresponding numeric classdgTMatrix where for such pairs, the correspondingx slot entries are added. For logical matrices, thexentries corresponding to duplicated index pairs(i,j) are“added” as well if the addition is defined as logicalor,i.e., “TRUE + TRUE |-> TRUE” and“TRUE + FALSE |-> TRUE”.Note the use ofasUniqueT() for getting an internallyunique representation without duplicated(i,j) entries.
Objects from the Class
Objects can be created by calls of the formnew("lgCMatrix", ...) and so on. More frequently objects are created by coercion ofa numeric sparse matrix to the logical form, e.g. in an expressionx != 0.
The logical form is also used in the symbolic analysis phaseof an algorithm involving sparse matrices. Such algorithms ofteninvolve two phases: a symbolic phase wherein the positions of thenon-zeros in the result are determined and a numeric phase wherein theactual results are calculated. During the symbolic phase only thepositions of the non-zero elements in any operands are of interest,hence any numeric sparse matrices can be treated as logical sparsematrices.
Slots
x:Object of class
"logical", i.e., eitherTRUE,NA, orFALSE.uplo:Object of class
"character". Must beeither "U", for upper triangular, and "L", for lowertriangular. Present in the triangular and symmetric classes but notin the general class.diag:Object of class
"character". Must beeither"U", for unit triangular (diagonal is all ones), or"N"for non-unit. The implicit diagonal elements are notexplicitly stored whendiagis"U". Present in thetriangular classes only.p:Object of class
"integer"of pointers, onefor each column (row), to the initial (zero-based) index of elements inthe column. Present in compressed column-oriented and compressedrow-oriented forms only.i:Object of class
"integer"of length nnzero(number of non-zero elements). These are the row numbers foreach TRUE element in the matrix. All other elements are FALSE.Present in triplet and compressed column-oriented forms only.j:Object of class
"integer"of length nnzero(number of non-zero elements). These are the column numbers foreach TRUE element in the matrix. All other elements are FALSE.Present in triplet and compressed row-oriented forms only.Dim:Object of class
"integer"- the dimensionsof the matrix.
Methods
- coerce
signature(from = "dgCMatrix", to = "lgCMatrix")- t
signature(x = "lgCMatrix"): returns the transposeofx- which
signature(x = "lsparseMatrix"), semanticallyequivalent tobase functionwhich(x, arr.ind);for details, see thelMatrixclass documentation.
See Also
the classdgCMatrix anddgTMatrix
Examples
(m <- Matrix(c(0,0,2:0), 3,5, dimnames=list(LETTERS[1:3],NULL)))(lm <- (m > 1)) # lgC!lm # no longer sparsestopifnot(is(lm,"lsparseMatrix"), identical(!lm, m <= 1))data(KNex, package = "Matrix")str(mmG.1 <- (KNex $ mm) > 0.1)# "lgC..."table(mmG.1@x)# however with many ``non-structural zeros''## from logical to nz_pattern -- okay when there are no NA's :nmG.1 <- as(mmG.1, "nMatrix") # <<< has "TRUE" also where mmG.1 had FALSE## from logical to "double"dmG.1 <- as(mmG.1, "dMatrix") # has '0' and back:lmG.1 <- as(dmG.1, "lMatrix")stopifnot(identical(nmG.1, as((KNex $ mm) != 0,"nMatrix")), validObject(lmG.1), identical(lmG.1, mmG.1))class(xnx <- crossprod(nmG.1))# "nsC.."class(xlx <- crossprod(mmG.1))# "dsC.." : numericis0 <- (xlx == 0)mean(as.vector(is0))# 99.3% zeros: quite sparse, buttable(xlx@x == 0)# more than half of the entries are (non-structural!) 0stopifnot(isSymmetric(xlx), isSymmetric(xnx), ## compare xnx and xlx : have the *same* non-structural 0s : sapply(slotNames(xnx), function(n) identical(slot(xnx, n), slot(xlx, n))))Symmetric Dense Logical Matrices
Description
The"lsyMatrix" class is the class of symmetric, dense logicalmatrices in non-packed storage and"lspMatrix" is the class ofof these in packed storage. In the packed form, only the uppertriangle or the lower triangle is stored.
Objects from the Class
Objects can be created by calls of the formnew("lsyMatrix", ...).
Slots
uplo:Object of class
"character". Must beeither "U", for upper triangular, and "L", for lower triangular.x:Object of class
"logical". The logicalvalues that constitute the matrix, stored in column-major order.Dim,Dimnames:The dimension (a length-2
"integer") and corresponding names (orNULL), see theMatrixclass.factors:Object of class
"list". A namedlist of factorizations that have been computed for the matrix.
Extends
Both extend classes"ldenseMatrix" and"symmetricMatrix", directly; further, class"Matrix" and others,indirectly. UseshowClass("lsyMatrix"), e.g., for details.
Methods
Currently, mainlyt() and coercion methods (foras(.); use, e.g.,showMethods(class="lsyMatrix") for details.
See Also
Examples
(M2 <- Matrix(c(TRUE, NA, FALSE, FALSE), 2, 2)) # logical dense (ltr)str(M2)# can(sM <- M2 | t(M2)) # "lge"as(sM, "symmetricMatrix")str(sM <- as(sM, "packedMatrix")) # packed symmetricTriangular Dense Logical Matrices
Description
The"ltrMatrix" class is the class of triangular, dense,logical matrices in nonpacked storage. The"ltpMatrix" classis the same except in packed storage.
Slots
x:Object of class
"logical". The logicalvalues that constitute the matrix, stored in column-major order.uplo:Object of class
"character". Must beeither "U", for upper triangular, and "L", for lower triangular.diag:Object of class
"character". Must beeither"U", for unit triangular (diagonal is all ones), or"N"; seetriangularMatrix.Dim,Dimnames:The dimension (a length-2
"integer") and corresponding names (orNULL), see theMatrixclass.factors:Object of class
"list". A namedlist of factorizations that have been computed for the matrix.
Extends
Both extend classes"ldenseMatrix" and"triangularMatrix", directly; further, class"Matrix","lMatrix" and others,indirectly. UseshowClass("ltrMatrix"), e.g.,for details.
Methods
Currently, mainlyt() and coercion methods (foras(.); use, e.g.,showMethods(class="ltrMatrix") for details.
See Also
ClasseslgeMatrix,Matrix;functiont
Examples
showClass("ltrMatrix")str(new("ltpMatrix"))(lutr <- as(upper.tri(matrix(, 4, 4)), "ldenseMatrix"))str(lutp <- pack(lutr)) # packed matrix: only 10 = 4*(4+1)/2 entries!lutp # the logical negation (is *not* logical triangular !)## but this one is:stopifnot(all.equal(lutp, pack(!!lutp)))Methods for LU Factorization
Description
Computes the pivoted LU factorization of anm \times nreal matrixA, which has the general form
P_{1} A P_{2} = L U
or (equivalently)
A = P_{1}' L U P_{2}'
whereP_{1} is anm \times m permutation matrix,P_{2} is ann \times n permutation matrix,L is anm \times \min(m,n)unit lower trapezoidal matrix, andU is a\min(m,n) \times nupper trapezoidal matrix.
Methods fordenseMatrix are built onLAPACK routinedgetrf, which does not permute columns,so thatP_{2} is an identity matrix.
Methods forsparseMatrix are built onCXSparse routinecs_lu, which requiresm = n,so thatL andU are triangular matrices.
Usage
lu(x, ...)## S4 method for signature 'dgeMatrix'lu(x, warnSing = TRUE, ...)## S4 method for signature 'dgCMatrix'lu(x, errSing = TRUE, order = NA_integer_, tol = 1, ...)## S4 method for signature 'dsyMatrix'lu(x, cache = TRUE, ...)## S4 method for signature 'dsCMatrix'lu(x, cache = TRUE, ...)## S4 method for signature 'matrix'lu(x, ...)Arguments
x | afinite matrix or |
warnSing | a logical indicating if awarning shouldbe signaled for singular |
errSing | a logical indicating if anerror shouldbe signaled for singular |
order | an integer in |
tol | a number. The original pivot element is usedif its absolute value exceeds |
cache | a logical indicating if the result should becached in |
... | further arguments passed to or from methods. |
Details
What happens whenx is determined to be near-singulardiffers by method. The method for classdgeMatrixcompletes the factorization, warning ifwarnSing = TRUEand in any case returning a validdenseLUobject. Users of this method can detect singularx witha suitable warning handler; seetryCatch.In contrast, the method for classdgCMatrixabandons further computation, throwing an error iferrSing = TRUEand otherwise returningNA. Users of this method candetect singularx with an error handler or by settingerrSing = FALSE and testing for a formal result withis(., "sparseLU").
Value
An object representing the factorization, inheriting fromvirtual classLU. The specific classisdenseLU unlessx inheritsfrom virtual classsparseMatrix,in which case it issparseLU.
References
The LAPACK source code, including documentation; seehttps://netlib.org/lapack/double/dgetrf.f.
Davis, T. A. (2006).Direct methods for sparse linear systems.Society for Industrial and Applied Mathematics.doi:10.1137/1.9780898718881
Golub, G. H., & Van Loan, C. F. (2013).Matrix computations (4th ed.).Johns Hopkins University Press.doi:10.56021/9781421407944
See Also
ClassesdenseLU andsparseLU and their methods.
ClassesdgeMatrix anddgCMatrix.
Generic functionsexpand1 andexpand2,for constructing matrix factors from the result.
Generic functionsCholesky,BunchKaufman,Schur, andqr,for computing other factorizations.
Examples
showMethods("lu", inherited = FALSE)set.seed(0)## ---- Dense ----------------------------------------------------------(A1 <- Matrix(rnorm(9L), 3L, 3L))(lu.A1 <- lu(A1))(A2 <- round(10 * A1[, -3L]))(lu.A2 <- lu(A2))## A ~ P1' L U in floating pointstr(e.lu.A2 <- expand2(lu.A2), max.level = 2L)stopifnot(all.equal(A2, Reduce(`%*%`, e.lu.A2)))## ---- Sparse ---------------------------------------------------------A3 <- as(readMM(system.file("external/pores_1.mtx", package = "Matrix")), "CsparseMatrix")(lu.A3 <- lu(A3))## A ~ P1' L U P2' in floating pointstr(e.lu.A3 <- expand2(lu.A3), max.level = 2L)stopifnot(all.equal(A3, Reduce(`%*%`, e.lu.A3)))Map Matrix to its Triplet Representation
Description
From anR object coercible to"TsparseMatrix",typically a (sparse) matrix, produce its triplet representation which maycollapse to a “Duplet” in the case of binary aka pattern, such as"nMatrix" objects.
Usage
mat2triplet(x, uniqT = FALSE)Arguments
x | anyR object for which |
uniqT |
|
Value
Alist, typically with three components,
i | vector of row indices for all non-zero entries of |
i | vector of columns indices for all non-zero entries of |
x | vector of all non-zero entries of |
Note that theorder of the entries is determined by thecoercion to"TsparseMatrix" and hence typicallywith increasingj (and increasingi within ties ofj).
Note
Themat2triplet() utility was created to be a more efficient andmore predictable substitute forsummary(<sparseMatrix>).UseRs have wrongly expected the latter to return a data frame withcolumnsi andj which however is wrong for a"diagonalMatrix".
See Also
Thesummary() method for"sparseMatrix",summary,sparseMatrix-method.
mat2triplet() is conceptually theinverse function ofspMatrix and (one case of)sparseMatrix.
Examples
mat2triplet # simple definitioni <- c(1,3:8); j <- c(2,9,6:10); x <- 7 * (1:7)(Ax <- sparseMatrix(i, j, x = x)) ## 8 x 10 "dgCMatrix"str(trA <- mat2triplet(Ax))stopifnot(i == sort(trA$i), sort(j) == trA$j, x == sort(trA$x))D <- Diagonal(x=4:2)summary(D)str(mat2triplet(D))Matrix (Cross) Products (of Transpose)
Description
The basic matrix product,%*% is implemented for all ourMatrix and also forsparseVector classes, fully analogously toR'sbasematrix and vector objects.
The functionscrossprod andtcrossprod arematrix products or “cross products”, ideally implementedefficiently without computingt(.)'s unnecessarily.They also returnsymmetricMatrix classedmatrices when easily detectable, e.g., incrossprod(m), the oneargument case.
tcrossprod() takes the cross-product of the transpose of a matrix.tcrossprod(x) is formally equivalent to, but faster than, thecallx %*% t(x), and so istcrossprod(x, y) instead ofx %*% t(y).
Boolean matrix products are computed via either%&% orboolArith = TRUE.
Usage
## S4 method for signature 'CsparseMatrix,diagonalMatrix'x %*% y## S4 method for signature 'CsparseMatrix,diagonalMatrix'crossprod(x, y = NULL, boolArith = NA, ...) ## .... and for many more signatures## S4 method for signature 'TsparseMatrix,missing'tcrossprod(x, y = NULL, boolArith = NA, ...) ## .... and for many more signaturesArguments
x | a matrix-like object |
y | a matrix-like object, or for |
boolArith |
|
... | potentially more arguments passed to and from methods. |
Details
For some classes in theMatrix package, such asdgCMatrix, it is much faster to calculate thecross-product of the transpose directly instead of calculating thetranspose first and then its cross-product.
boolArith = TRUE for regular (“non cross”) matrixproducts,%*% cannot be specified. Instead, we provide the%&% operator forboolean matrix products.
Value
AMatrix object, in the one argument caseof an appropriatesymmetric matrix class, i.e., inheriting fromsymmetricMatrix.
Methods
- %*%
signature(x = "dgeMatrix", y = "dgeMatrix"):Matrix multiplication; ditto for several other signaturecombinations, seeshowMethods("%*%", class = "dgeMatrix").- %*%
signature(x = "dtrMatrix", y = "matrix")and othersignatures (useshowMethods("%*%",)):matrix multiplication. Multiplication of (matching) triangularmatrices now should remain triangular (in the sense of classtriangularMatrix).- crossprod
signature(x = "dgeMatrix", y = "dgeMatrix"):ditto for several other signatures, useshowMethods("crossprod", class = "dgeMatrix"), matrixcrossproduct, an efficient version oft(x) %*% y.- crossprod
signature(x = "CsparseMatrix", y = "missing")returnst(x) %*% xas andsCMatrixobject.- crossprod
signature(x = "TsparseMatrix", y = "missing")returnst(x) %*% xas andsCMatrixobject.- crossprod,tcrossprod
signature(x = "dtrMatrix", y = "matrix")and other signatures, see"%*%"above.
Note
boolArith = TRUE,FALSE orNA has been newlyintroduced forMatrix 1.2.0 (March 2015). Its implementationhas still not been tested extensively. Notably the behaviour forsparse matrices withx slots containing extra zeros had not beendocumented previously, see the%&% help page.
Currently,boolArith = TRUE is implemented viaCsparseMatrix coercions which may be quiteinefficient for dense matrices. Contributions for efficiencyimprovements are welcome.
See Also
tcrossprod inR's base, andcrossprod and%*%.Matrix package%&% for boolean matrix productmethods.
Examples
## A random sparse "incidence" matrix : m <- matrix(0, 400, 500) set.seed(12) m[runif(314, 0, length(m))] <- 1 mm <- as(m, "CsparseMatrix") object.size(m) / object.size(mm) # smaller by a factor of > 200 ## tcrossprod() is very fast: system.time(tCmm <- tcrossprod(mm))# 0 (PIII, 933 MHz) system.time(cm <- crossprod(t(m))) # 0.16 system.time(cm. <- tcrossprod(m)) # 0.02 stopifnot(cm == as(tCmm, "matrix")) ## show sparse sub matrix tCmm[1:16, 1:30]Class "nMatrix" of Non-zero Pattern Matrices
Description
ThenMatrix class is the virtual “mother” class of allnon-zero pattern (or simplypattern)matrices in theMatrix package.
Slots
Common toall matrix object in the package:
Dim:Object of class
"integer"- the dimensionsof the matrix - must be an integer vector with exactly twonon-negative values.Dimnames:list of length two; each componentcontaining NULL or a
charactervector lengthequal the correspondingDimelement.
Methods
- coerce
signature(from = "matrix", to = "nMatrix"):Note that these coercions (must) coerceNAs tonon-zero, hence conceptuallyTRUE.This is particularly important whensparseMatrixobjects are coerced to"nMatrix"and hence tonsparseMatrix.
— — —
Additional methods contain group methods, such as
- Ops
signature(e1 = "nMatrix", e2 = "...."), ...- Arith
signature(e1 = "nMatrix", e2 = "...."), ...- Compare
signature(e1 = "nMatrix", e2 = "...."), ...- Logic
signature(e1 = "nMatrix", e2 = "...."), ...- Summary
signature(x = "nMatrix", "...."), ...
See Also
The classeslMatrix,nsparseMatrix, and the mother class,Matrix.
Examples
getClass("nMatrix")L3 <- Matrix(upper.tri(diag(3)))L3 # an "ltCMatrix"as(L3, "nMatrix") # -> ntC*## similar, not using Matrix()as(upper.tri(diag(3)), "nMatrix")# currently "ngTMatrix"Virtual Class "ndenseMatrix" of Dense Logical Matrices
Description
ndenseMatrix is the virtual class of all denselogical(S4) matrices. It extends bothdenseMatrixandlMatrix directly.
Slots
x:logical vector containing the entries of the matrix.
Dim,Dimnames:see
Matrix.
Extends
Class"nMatrix", directly.Class"denseMatrix", directly.Class"Matrix", by class"nMatrix".Class"Matrix", by class"denseMatrix".
Methods
- %*%
signature(x = "nsparseMatrix", y = "ndenseMatrix"): ...- %*%
signature(x = "ndenseMatrix", y = "nsparseMatrix"): ...- crossprod
signature(x = "nsparseMatrix", y = "ndenseMatrix"): ...- crossprod
signature(x = "ndenseMatrix", y = "nsparseMatrix"): ...- as.vector
signature(x = "ndenseMatrix", mode = "missing"): ...- diag
signature(x = "ndenseMatrix"): extracts thediagonal as for all matrices, see the genericdiag().- which
signature(x = "ndenseMatrix"), semanticallyequivalent tobase functionwhich(x, arr.ind);for details, see thelMatrixclass documentation.
See Also
ClassngeMatrix and the other subclasses.
Examples
showClass("ndenseMatrix")as(diag(3) > 0, "ndenseMatrix")# -> "nge"Nearest Positive Definite Matrix
Description
Compute the nearest positive definite matrix to an approximateone, typically a correlation or variance-covariance matrix.
Usage
nearPD(x, corr = FALSE, keepDiag = FALSE, base.matrix = FALSE, do2eigen = TRUE, doSym = FALSE, doDykstra = TRUE, only.values = FALSE, ensureSymmetry = !isSymmetric(x), eig.tol = 1e-06, conv.tol = 1e-07, posd.tol = 1e-08, maxit = 100, conv.norm.type = "I", trace = FALSE)Arguments
x | numeric |
corr | logical indicating if the matrix should be acorrelation matrix. |
keepDiag | logical, generalizing |
base.matrix | logical indicating if the resulting |
do2eigen | logical indicating if a |
doSym | logical indicating if |
doDykstra | logical indicating if Dykstra's correction should beused; true by default. If false, the algorithm is basically thedirect fixpoint iteration |
only.values | logical; if |
ensureSymmetry | logical; by default, |
eig.tol | defines relative positiveness of eigenvalues comparedto largest one, |
conv.tol | convergence tolerance for Higham algorithm. |
posd.tol | tolerance for enforcing positive definiteness (in thefinal |
maxit | maximum number of iterations allowed. |
conv.norm.type | convergence norm type ( |
trace | logical or integer specifying if convergence monitoringshould be traced. |
Details
This implements the algorithm of Higham (2002), and then (ifdo2eigen is true) forces positive definiteness using code fromposdefify. The algorithm of Knol and tenBerge (1989) (not implemented here) is more general in that itallows constraints to (1) fix some rows (and columns) of the matrix and(2) force the smallest eigenvalue to have a certain value.
Note that settingcorr = TRUE just setsdiag(.) <- 1within the algorithm.
Higham (2002) uses Dykstra's correction, but the version by JensOehlschlägel did not use it (accidentally),and still gave reasonable results; this simplification, now onlyused ifdoDykstra = FALSE,was active innearPD() up to Matrix version 0.999375-40.
Value
Ifonly.values = TRUE, a numeric vector of eigenvalues of theapproximating matrix;Otherwise, as by default, an S3 object ofclass"nearPD", basically a list with components
mat | a matrix of class |
eigenvalues | numeric vector of eigenvalues of |
corr | logical, just the argument |
normF | the Frobenius norm ( |
iterations | number of iterations needed. |
converged | logical indicating if iterations converged. |
Author(s)
Jens Oehlschlägel donated a first version.Subsequent changes by the Matrix package authors.
References
Cheng, Sheung Hun and Higham, Nick (1998)A Modified Cholesky Algorithm Based on a Symmetric Indefinite Factorization;SIAM J. Matrix Anal.\ Appl.,19, 1097–1110.
Knol DL, ten Berge JMF (1989)Least-squares approximation of an improper correlation matrix by aproper one.Psychometrika54, 53–61.
Higham, Nick (2002)Computing the nearest correlation matrix - a problem from finance;IMA Journal of Numerical Analysis22, 329–343.
See Also
A first version of this (with non-optionalcorr=TRUE)has been available asnearcor(); andmore simple versions with a similar purposeposdefify(), both from packagesfsmisc.
Examples
## Higham(2002), p.334f - simple example A <- matrix(1, 3,3); A[1,3] <- A[3,1] <- 0 n.A <- nearPD(A, corr=TRUE, do2eigen=FALSE) n.A[c("mat", "normF")] n.A.m <- nearPD(A, corr=TRUE, do2eigen=FALSE, base.matrix=TRUE)$mat stopifnot(exprs = { #=-------------- all.equal(n.A$mat[1,2], 0.760689917) all.equal(n.A$normF, 0.52779033, tolerance=1e-9) all.equal(n.A.m, unname(as.matrix(n.A$mat)), tolerance = 1e-15)# seen rel.d.= 1.46e-16 }) set.seed(27) m <- matrix(round(rnorm(25),2), 5, 5) m <- m + t(m) diag(m) <- pmax(0, diag(m)) + 1 (m <- round(cov2cor(m), 2)) str(near.m <- nearPD(m, trace = TRUE)) round(near.m$mat, 2) norm(m - near.m$mat) # 1.102 / 1.08 if(requireNamespace("sfsmisc")) { m2 <- sfsmisc::posdefify(m) # a simpler approach norm(m - m2) # 1.185, i.e., slightly "less near" } round(nearPD(m, only.values=TRUE), 9)## A longer example, extended from Jens' original,## showing the effects of some of the options:pr <- Matrix(c(1, 0.477, 0.644, 0.478, 0.651, 0.826, 0.477, 1, 0.516, 0.233, 0.682, 0.75, 0.644, 0.516, 1, 0.599, 0.581, 0.742, 0.478, 0.233, 0.599, 1, 0.741, 0.8, 0.651, 0.682, 0.581, 0.741, 1, 0.798, 0.826, 0.75, 0.742, 0.8, 0.798, 1), nrow = 6, ncol = 6)nc. <- nearPD(pr, conv.tol = 1e-7) # defaultnc.$iterations # 2nc.1 <- nearPD(pr, conv.tol = 1e-7, corr = TRUE)nc.1$iterations # 11 / 12 (!)ncr <- nearPD(pr, conv.tol = 1e-15)str(ncr)# still 2 iterationsncr.1 <- nearPD(pr, conv.tol = 1e-15, corr = TRUE)ncr.1 $ iterations # 27 / 30 !ncF <- nearPD(pr, conv.tol = 1e-15, conv.norm = "F")stopifnot(all.equal(ncr, ncF))# norm type does not matter at all in this example## But indeed, the 'corr = TRUE' constraint did ensure a better solution;## cov2cor() does not just fix it up equivalently :norm(pr - cov2cor(ncr$mat)) # = 0.09994norm(pr - ncr.1$mat) # = 0.08746 / 0.08805### 3) a real data example from a 'systemfit' model (3 eq.):(load(system.file("external", "symW.rda", package="Matrix"))) # "symW"dim(symW) # 24 x 24class(symW)# "dsCMatrix": sparse symmetricif(dev.interactive()) image(symW)EV <- eigen(symW, only=TRUE)$valuessummary(EV) ## looking more closely {EV sorted decreasingly}:tail(EV)# all 6 are negativeEV2 <- eigen(sWpos <- nearPD(symW)$mat, only=TRUE)$valuesstopifnot(EV2 > 0)if(requireNamespace("sfsmisc")) { plot(pmax(1e-3,EV), EV2, type="o", log="xy", xaxt="n", yaxt="n") for(side in 1:2) sfsmisc::eaxis(side)} else plot(pmax(1e-3,EV), EV2, type="o", log="xy")abline(0, 1, col="red3", lty=2)Class "ngeMatrix" of General Dense Nonzero-pattern Matrices
Description
This is the class of general dense nonzero-patternmatrices, seenMatrix.
Slots
x:Object of class
"logical". The logicalvalues that constitute the matrix, stored in column-major order.Dim,Dimnames:The dimension (a length-2
"integer") and corresponding names (orNULL), see theMatrixclass.factors:Object of class
"list". A namedlist of factorizations that have been computed for the matrix.
Extends
Class"ndenseMatrix", directly.Class"lMatrix", by class"ndenseMatrix".Class"denseMatrix", by class"ndenseMatrix".Class"Matrix", by class"ndenseMatrix".Class"Matrix", by class"ndenseMatrix".
Methods
Currently, mainlyt() and coercion methods (foras(.)); use, e.g.,showMethods(class="ngeMatrix") for details.
See Also
Non-general logical dense matrix classes such asntrMatrix, ornsyMatrix;sparse logical classes such asngCMatrix.
Examples
showClass("ngeMatrix")## "lgeMatrix" is really more relevantThe Number of Non-Zero Values of a Matrix
Description
Returns the number of non-zero values of a numeric-likeR object, andin particular an objectx inheriting from classMatrix.
Usage
nnzero(x, na.counted = NA)Arguments
x | anR object, typically inheriting from class |
na.counted | a
For sparse matrices, you may often want to use |
Value
the number of non zero entries inx (typicallyinteger).
Note that for asymmetric sparse matrixS (i.e., inheriting fromclasssymmetricMatrix),nnzero(S) istypicallytwice thelength(S@x).
Methods
signature(x = "ANY")the default method fornon-
Matrixclass objects, simply counts thenumber0s inx, countingNA's depending onthena.countedargument, see above.signature(x = "denseMatrix")conceptually the same asfor traditional
matrixobjects, care has to be takenfor"symmetricMatrix"objects.signature(x = "diagonalMatrix"), andsignature(x = "indMatrix")fast simple methods for thesespecial
"sparseMatrix"classes.signature(x = "sparseMatrix")typically, the mostinteresting method, also carefully taking
"symmetricMatrix"objects into account.
See Also
TheMatrix class also has alength method; typically,length(M) is muchlarger thannnzero(M) for a sparse matrix M, and the latter isa better indication of thesize ofM.
Examples
m <- Matrix(0+1:28, nrow = 4)m[-3,c(2,4:5,7)] <- m[ 3, 1:4] <- m[1:3, 6] <- 0(mT <- as(m, "TsparseMatrix"))nnzero(mT)(S <- crossprod(mT))nnzero(S)str(S) # slots are smaller than nnzero()stopifnot(nnzero(S) == sum(as.matrix(S) != 0))# failed earlierdata(KNex, package = "Matrix")M <- KNex$mmclass(M)dim(M)length(M); stopifnot(length(M) == prod(dim(M)))nnzero(M) # more relevant than length## the above are also visible fromstr(M)Matrix Norms
Description
Computes a matrix norm ofx, using Lapack for dense matrices.The norm can be the one ("O", or"1") norm, theinfinity ("I") norm, the Frobenius ("F") norm,the maximum modulus ("M") among elements of a matrix, or thespectral norm or 2-norm ("2"), as determined by the value oftype.
Usage
norm(x, type, ...)Arguments
x | a real or complex matrix. |
type | A character indicating the type of norm desired.
The default is |
... | further arguments passed to or from other methods. |
Details
For dense matrices, the methods eventually call the Lapack functionsdlange,dlansy,dlantr,zlange,zlansy, andzlantr.
Value
A numeric value of class"norm", representing the quantitychosen according totype.
References
Anderson, E., et al. (1994).LAPACK User's Guide,2nd edition, SIAM, Philadelphia.
See Also
onenormest(), anapproximate randomized estimateof the 1-norm condition number, efficient for large sparse matrices.
Thenorm() function fromR'sbase package.
Examples
x <- Hilbert(9)norm(x)# = "O" = "1"stopifnot(identical(norm(x), norm(x, "1")))norm(x, "I")# the same, because 'x' is symmetricallnorms <- function(x) { ## norm(NA, "2") did not work until R 4.0.0 do2 <- getRversion() >= "4.0.0" || !anyNA(x) vapply(c("1", "I", "F", "M", if(do2) "2"), norm, 0, x = x)}allnorms(x)allnorms(Hilbert(10))i <- c(1,3:8); j <- c(2,9,6:10); x <- 7 * (1:7)A <- sparseMatrix(i, j, x = x) ## 8 x 10 "dgCMatrix"(sA <- sparseMatrix(i, j, x = x, symmetric = TRUE)) ## 10 x 10 "dsCMatrix"(tA <- sparseMatrix(i, j, x = x, triangular= TRUE)) ## 10 x 10 "dtCMatrix"(allnorms(A) -> nA)allnorms(sA)allnorms(tA)stopifnot(all.equal(nA, allnorms(as(A, "matrix"))), all.equal(nA, allnorms(tA))) # because tA == rbind(A, 0, 0)A. <- A; A.[1,3] <- NAstopifnot(is.na(allnorms(A.))) # gave errorSparse "pattern" Matrices
Description
ThensparseMatrix class is a virtual class of sparse“pattern” matrices, i.e., binary matrices conceptuallywithTRUE/FALSE entries. Only the positions of theelements that areTRUE are stored.
These can be stored in the “triplet” form(TsparseMatrix, subclassesngTMatrix,nsTMatrix, andntTMatrix which really contain pairs, nottriplets) or in compressed column-oriented form (classCsparseMatrix, subclassesngCMatrix,nsCMatrix, andntCMatrix) or–rarely–incompressed row-oriented form (classRsparseMatrix,subclassesngRMatrix,nsRMatrix, andntRMatrix).The second letter in the name of these non-virtual classes indicatesgeneral,symmetric, ortriangular.
Objects from the Class
Objects can be created by calls of the formnew("ngCMatrix", ...) and so on. More frequently objects are created by coercion ofa numeric sparse matrix to the pattern form for use inthe symbolic analysis phaseof an algorithm involving sparse matrices. Such algorithms ofteninvolve two phases: a symbolic phase wherein the positions of thenon-zeros in the result are determined and a numeric phase wherein theactual results are calculated. During the symbolic phase only thepositions of the non-zero elements in any operands are of interest,hence numeric sparse matrices can be treated as sparse patternmatrices.
Slots
uplo:Object of class
"character". Must beeither "U", for upper triangular, and "L", for lowertriangular. Present in the triangular and symmetric classes but notin the general class.diag:Object of class
"character". Must beeither"U", for unit triangular (diagonal is all ones), or"N"for non-unit. The implicit diagonal elements are notexplicitly stored whendiagis"U". Present in thetriangular classes only.p:Object of class
"integer"of pointers, onefor each column (row), to the initial (zero-based) index of elements inthe column. Present in compressed column-oriented and compressedrow-oriented forms only.i:Object of class
"integer"of length nnzero(number of non-zero elements). These are the row numbers foreach TRUE element in the matrix. All other elements are FALSE.Present in triplet and compressed column-oriented forms only.j:Object of class
"integer"of length nnzero(number of non-zero elements). These are the column numbers foreach TRUE element in the matrix. All other elements are FALSE.Present in triplet and compressed row-oriented forms only.Dim:Object of class
"integer"- the dimensionsof the matrix.
Methods
- coerce
signature(from = "dgCMatrix", to ="ngCMatrix"), and many similar ones; typically you shouldcoerce to"nsparseMatrix"(or"nMatrix"). Note thatcoercion to a sparse pattern matrix records all the potentialnon-zero entries, i.e., explicit (“non-structural”) zeroesare coerced toTRUE, notFALSE, see the example.- t
signature(x = "ngCMatrix"): returns the transposeofx- which
signature(x = "lsparseMatrix"), semanticallyequivalent tobase functionwhich(x, arr.ind);for details, see thelMatrixclass documentation.
See Also
the classdgCMatrix
Examples
(m <- Matrix(c(0,0,2:0), 3,5, dimnames=list(LETTERS[1:3],NULL)))## ``extract the nonzero-pattern of (m) into an nMatrix'':nm <- as(m, "nsparseMatrix") ## -> will be a "ngCMatrix"str(nm) # no 'x' slotnnm <- !nm # no longer sparse## consistency check:stopifnot(xor(as( nm, "matrix"), as(nnm, "matrix")))## low-level way of adding "non-structural zeros" :nnm <- as(nnm, "lsparseMatrix") # "lgCMatrix"nnm@x[2:4] <- c(FALSE, NA, NA)nnmas(nnm, "nMatrix") # NAs *and* non-structural 0 |---> 'TRUE'data(KNex, package = "Matrix")nmm <- as(KNex $ mm, "nMatrix")str(xlx <- crossprod(nmm))# "nsCMatrix"stopifnot(isSymmetric(xlx))image(xlx, main=paste("crossprod(nmm) : Sparse", class(xlx)))Symmetric Dense Nonzero-Pattern Matrices
Description
The"nsyMatrix" class is the class of symmetric, dense nonzero-patternmatrices in non-packed storage and"nspMatrix" is the class ofof these in packed storage. Only the upper triangle or thelower triangle is stored.
Objects from the Class
Objects can be created by calls of the formnew("nsyMatrix", ...).
Slots
uplo:Object of class
"character". Must beeither "U", for upper triangular, and "L", for lower triangular.x:Object of class
"logical". The logicalvalues that constitute the matrix, stored in column-major order.Dim,Dimnames:The dimension (a length-2
"integer") and corresponding names (orNULL), see theMatrixclass.factors:Object of class
"list". A namedlist of factorizations that have been computed for the matrix.
Extends
"nsyMatrix" extends class"ngeMatrix", directly, whereas"nspMatrix" extends class"ndenseMatrix", directly.
Both extend class"symmetricMatrix", directly,and class"Matrix" and others,indirectly, useshowClass("nsyMatrix"), e.g., for details.
Methods
Currently, mainlyt() and coercion methods (foras(.); use, e.g.,showMethods(class="nsyMatrix") for details.
See Also
Examples
(s0 <- new("nsyMatrix"))(M2 <- Matrix(c(TRUE, NA, FALSE, FALSE), 2, 2)) # logical dense (ltr)(sM <- M2 & t(M2)) # -> "lge"class(sM <- as(sM, "nMatrix")) # -> "nge" (sM <- as(sM, "symmetricMatrix")) # -> "nsy"str(sM <- as(sM, "packedMatrix")) # -> "nsp", i.e., packed symmetricTriangular Dense Logical Matrices
Description
The"ntrMatrix" class is the class of triangular, dense,logical matrices in nonpacked storage. The"ntpMatrix" classis the same except in packed storage.
Slots
x:Object of class
"logical". The logicalvalues that constitute the matrix, stored in column-major order.uplo:Object of class
"character". Must beeither "U", for upper triangular, and "L", for lower triangular.diag:Object of class
"character". Must beeither"U", for unit triangular (diagonal is all ones), or"N"; seetriangularMatrix.Dim,Dimnames:The dimension (a length-2
"integer") and corresponding names (orNULL), see theMatrixclass.factors:Object of class
"list". A namedlist of factorizations that have been computed for the matrix.
Extends
"ntrMatrix" extends class"ngeMatrix", directly, whereas"ntpMatrix" extends class"ndenseMatrix", directly.
Both extend Class"triangularMatrix", directly,and class"denseMatrix","lMatrix" and others,indirectly, useshowClass("nsyMatrix"), e.g., fordetails.
Methods
Currently, mainlyt() and coercion methods (foras(.); use, e.g.,showMethods(class="ntrMatrix") for details.
See Also
ClassesngeMatrix,Matrix;functiont
Examples
showClass("ntrMatrix")str(new("ntpMatrix"))(nutr <- as(upper.tri(matrix(, 4, 4)), "ndenseMatrix"))str(nutp <- pack(nutr)) # packed matrix: only 10 = 4*(4+1)/2 entries!nutp # the logical negation (is *not* logical triangular !)## but this one is:stopifnot(all.equal(nutp, pack(!!nutp)))Permutation matrices
Description
ThepMatrix class is the class ofpermutation matrices,stored as 1-based integer permutation vectors. A permutationmatrix is a square matrix whose rowsand columns are allstandard unit vectors. It follows that permutation matrices area special case ofindex matrices (hencepMatrixis defined as a direct subclass ofindMatrix).
Multiplying a matrix on the left by a permutation matrix isequivalent to permuting its rows. Analogously, multiplying amatrix on the right by a permutation matrix is equivalent topermuting its columns. Indeed, such products are implemented inMatrix as indexing operations; see ‘Details’ below.
Details
By definition, a permutation matrix is both a row index matrixand a column index matrix. However, theperm slot ofapMatrix cannot be used interchangeably as a row indexvector and column index vector. Ifmargin=1, thenperm is a row index vector, and the corresponding columnindex vector can be computed asinvPerm(perm), i.e.,by inverting the permutation. Analogously, ifmargin=2,thenperm andinvPerm(perm) are column and rowindex vectors, respectively.
Given ann-by-n row permutation matrixPwithperm slotp and a matrixM withconformable dimensions, we have
P M | = | P %*% M | = | M[p, ] |
M P | = | M %*% P | = | M[, i(p)] |
P'M | = | crossprod(P, M) | = | M[i(p), ] |
MP' | = | tcrossprod(M, P) | = | M[, p] |
P'P | = | crossprod(P) | = | Diagonal(n) |
PP' | = | tcrossprod(P) | = | Diagonal(n) |
wherei := invPerm.
Objects from the Class
Objects can be created explicitly with calls of the formnew("pMatrix", ...), but they are more commonly createdby coercing 1-based integer index vectors, with calls of theformas(., "pMatrix"); see ‘Methods’ below.
Slots
margin,perminherited from superclass
indMatrix. Here,permis aninteger vector of lengthDim[1]and a permutationof1:Dim[1].Dim,Dimnamesinherited from virtualsuperclass
Matrix.
Extends
Class"indMatrix", directly.
Methods
%*%signature(x = "pMatrix", y = "Matrix")and others listed byshowMethods("%*%", classes = "pMatrix"):matrix products implemented where appropriate as indexing operations.coercesignature(from = "numeric", to = "pMatrix"):supporting typicalpMatrixconstruction from a vectorof positive integers, specifically a permutation of1:n.Row permutation is assumed.- t
signature(x = "pMatrix"):the transpose, which is apMatrixwith identicalpermbut oppositemargin. Coincides withthe inverse, as permutation matrices are orthogonal.- solve
signature(a = "pMatrix", b = "missing"):the inverse permutation matrix, which is apMatrixwith identicalpermbut oppositemargin.Coincides with the transpose, as permutation matrices areorthogonal. SeeshowMethods("solve", classes = "pMatrix")for more signatures.- determinant
signature(x = "pMatrix", logarithm = "logical"):always returning 1 or -1, as permutation matrices are orthogonal. In fact, the result is exactly thesign of the permutation.
See Also
SuperclassindMatrix of index matrices,for many inherited methods;invPerm, for computinginverse permutation vectors.
Examples
(pm1 <- as(as.integer(c(2,3,1)), "pMatrix"))t(pm1) # is the same assolve(pm1)pm1 %*% t(pm1) # check that the transpose is the inversestopifnot(all(diag(3) == as(pm1 %*% t(pm1), "matrix")), is.logical(as(pm1, "matrix")))set.seed(11)## random permutation matrix :(p10 <- as(sample(10),"pMatrix"))## Permute rows / columns of a numeric matrix :(mm <- round(array(rnorm(3 * 3), c(3, 3)), 2))mm %*% pm1pm1 %*% mmtry(as(as.integer(c(3,3,1)), "pMatrix"))# Error: not a permutationas(pm1, "TsparseMatrix")p10[1:7, 1:4] # gives an "ngTMatrix" (most economic!)## row-indexing of a <pMatrix> keeps it as an <indMatrix>:p10[1:3, ]Representation of Packed and Unpacked Dense Matrices
Description
pack() coerces dense symmetric and dense triangular matricesfrom unpacked format (storing the full matrix) to packed format(storing only one of the upper and lower triangles).unpack()performs the reverse coercion. The two formats are formalizedby the virtual classes"packedMatrix" and"unpackedMatrix".
Usage
pack(x, ...)## S4 method for signature 'dgeMatrix'pack(x, symmetric = NA, upperTri = NA, ...)## S4 method for signature 'lgeMatrix'pack(x, symmetric = NA, upperTri = NA, ...)## S4 method for signature 'ngeMatrix'pack(x, symmetric = NA, upperTri = NA, ...)## S4 method for signature 'matrix'pack(x, symmetric = NA, upperTri = NA, ...)unpack(x, ...)Arguments
x | A dense symmetric or dense triangular matrix.
|
symmetric | logical (including |
upperTri | (for triangular |
... | further arguments passed to or from other methods. |
Details
pack(x) checks matricesxnot inheriting fromone of the virtual classes"symmetricMatrix""triangularMatrix" for symmetry(viaisSymmetric())then for upper and lower triangularity(viaisTriangular()) in order to identify a suitablecoercion. Setting one or both ofsymmetric andupperTritoTRUE orFALSE rather thanNA allows skippingof irrelevant tests for large matrices known to be symmetric or(upper or lower) triangular.
Users shouldnot assume thatpack() andunpack()are inverse operations. Specifically,y <- unpack(pack(x))may not reproduce an"unpackedMatrix"x in the sense ofidentical(). See the examples.
Value
- For
pack(): a
"packedMatrix"givingthe condensed representation ofx.- For
unpack(): an
"unpackedMatrix"givingthe full storage representation ofx.
Examples
showMethods("pack")(s <- crossprod(matrix(sample(15), 5,3))) # traditional symmetric matrix(sp <- pack(s))mt <- as.matrix(tt <- tril(s))(pt <- pack(mt))stopifnot(identical(pt, pack(tt)), dim(s ) == dim(sp), all(s == sp), dim(mt) == dim(pt), all(mt == pt), all(mt == tt))showMethods("unpack")(cp4 <- chol(Hilbert(4))) # is triangulartp4 <- pack(cp4) # [t]riangular [p]ackedstr(tp4)(unpack(tp4))stopifnot(identical(tp4, pack(unpack(tp4))))z1 <- new("dsyMatrix", Dim = c(2L, 2L), x = as.double(1:4), uplo = "U")z2 <- unpack(pack(z1))stopifnot(!identical(z1, z2), # _not_ identical all(z1 == z2)) # but mathematically equalcbind(z1@x, z2@x) # (unused!) lower triangle is "lost" in translationVirtual Class"packedMatrix" of Packed Dense Matrices
Description
Class"packedMatrix" is thevirtual class of densesymmetric or triangular matrices in "packed" format, storing onlythechoose(n+1,2) == n*(n+1)/2 elements of the upper orlower triangle of ann-by-n matrix. It is used todefine common methods for efficient subsetting, transposing, etc.of itsproper subclasses: currently"[dln]spMatrix"(packed symmetric),"[dln]tpMatrix" (packed triangular),and subclasses of these, such as"dppMatrix".
Slots
uplo:"character"; either "U", for upper triangular, and "L", for lower.Dim,Dimnames:as all
Matrixobjects.
Extends
Class"denseMatrix", directly.Class"Matrix", by class"denseMatrix",distance 2.
Methods
- pack
signature(x = "packedMatrix"): ...- unpack
signature(x = "packedMatrix"): ...- isSymmetric
signature(object = "packedMatrix"): ...- isTriangular
signature(object = "packedMatrix"): ...- isDiagonal
signature(object = "packedMatrix"): ...- t
signature(x = "packedMatrix"): ...- diag
signature(x = "packedMatrix"): ...- diag<-
signature(x = "packedMatrix"): ...
Author(s)
Mikael Jagan
See Also
pack andunpack; its virtual "complement""unpackedMatrix"; its proper subclasses"dspMatrix","ltpMatrix", etc.
Examples
showClass("packedMatrix")showMethods(classes = "packedMatrix")Format and Print Sparse Matrices Flexibly
Description
Format and print sparse matrices flexibly. These are the “workhorses” used bytheformat,show andprintmethods for sparse matrices. Ifx is large,printSpMatrix2(x) callsprintSpMatrix() twice, namely,for the first and the last few rows, suppressing those in between, andalso suppresses columns whenx is too wide.
printSpMatrix() basically prints the result offormatSpMatrix().
Usage
formatSpMatrix(x, digits = NULL, maxp = 1e9, cld = getClassDef(class(x)), zero.print = ".", col.names, note.dropping.colnames = TRUE, uniDiag = TRUE, align = c("fancy", "right"), ...)printSpMatrix(x, digits = NULL, maxp = max(100L, getOption("max.print")), cld = getClassDef(class(x)), zero.print = ".", col.names, note.dropping.colnames = TRUE, uniDiag = TRUE, col.trailer = "", align = c("fancy", "right"), ...)printSpMatrix2(x, digits = NULL, maxp = max(100L, getOption("max.print")), zero.print = ".", col.names, note.dropping.colnames = TRUE, uniDiag = TRUE, suppRows = NULL, suppCols = NULL, col.trailer = if(suppCols) "......" else "", align = c("fancy", "right"), width = getOption("width"), fitWidth = TRUE, ...)Arguments
x | anR object inheriting from class |
digits | significant digits to use for printing, see |
maxp | integer, default from |
cld | the class definition of |
zero.print | character which should be printed forstructural zeroes. The default |
col.names | logical or string specifying if and how column names of |
note.dropping.colnames | logical specifying, when |
uniDiag | logical indicating if the diagonal entries of a sparseunit triangular or unit-diagonal matrix should be formatted as |
col.trailer | a string to be appended to the right of eachcolumn; this is typically made use of by |
suppRows,suppCols | logicals or |
align | a string specifying how the |
width | number, a positive integer, indicating the approximatelydesired (line) width of the output, see also |
fitWidth | logical indicating if some effort should be made tomatch the desired |
... | unused optional arguments. |
Details
- formatSpMatrix:
If
xis large, only the first rows making up theapproximately firstmaxpentries is used, otherwise all ofx..formatSparseSimple()is applied to (a dense versionof) the matrix. Then,formatSparseMis used, unlessin trivial cases or for sparse matrices withoutxslot.
Value
formatSpMatrix() | returns a character matrix with possibly emptycolumn names, depending on |
printSpMatrix*() | return |
Author(s)
Martin Maechler
See Also
the virtual classsparseMatrix and theclasses extending it; maybesparseMatrix orspMatrix as simple constructors of such matrices.
The underlying utilitiesformatSparseM and.formatSparseSimple() (on the same page).
Examples
f1 <- gl(5, 3, labels = LETTERS[1:5])X <- as(f1, "sparseMatrix")X ## <==> show(X) <==> print(X)t(X) ## shows column names, since only 5 columnsX2 <- as(gl(12, 3, labels = paste(LETTERS[1:12],"c",sep=".")), "sparseMatrix")X2## less nice, but possible:print(X2, col.names = TRUE) # use [,1] [,2] .. => does not fit## Possibilities with column names printing: t(X2) # suppressing column namesprint(t(X2), col.names=TRUE)print(t(X2), zero.print = "", col.names="abbr. 1")print(t(X2), zero.print = "-", col.names="substring 2")Methods for QR Factorization
Description
Computes the pivoted QR factorization of anm \times nreal matrixA, which has the general form
P_{1} A P_{2} = Q R
or (equivalently)
A = P_{1}' Q R P_{2}'
whereP_{1} andP_{2} are permutation matrices,Q = \prod_{j = 1}^{n} H_{j}is anm \times m orthogonal matrixequal to the product ofn Householder matricesH_{j}, andR is anm \times n upper trapezoidal matrix.
denseMatrix use the default method implementedinbase, namelyqr.default. It is built onLINPACK routinedqrdc and LAPACK routinedgeqp3, whichdo not pivot rows, so thatP_{1} is an identity matrix.
Methods forsparseMatrix are built onCXSparse routinescs_sqr andcs_qr, which requirem \ge n.
Usage
qr(x, ...)## S4 method for signature 'dgCMatrix'qr(x, order = 3L, ...)Arguments
x | afinite matrix or |
order | an integer in |
... | further arguments passed to or from methods. |
Details
Ifx is sparse and structurally rank deficient, havingstructural rankr < n, thenx is augmented with(n-r) rows of (partly non-structural) zeros, such thatthe augmented matrix has structural rankn.This augmented matrix is factorized as described above:
P_1 A P_2 = P_1 \begin{bmatrix} A_{0} \\ 0 \end{bmatrix} P_2 = Q R
whereA_0 denotes the original, user-supplied(m-(n-r)) \times n matrix.
Value
An object representing the factorization, inheriting fromvirtual S4 classQR or S3 classqr. The specific class isqrunlessx inherits from virtual classsparseMatrix, in which case it issparseQR.
References
Davis, T. A. (2006).Direct methods for sparse linear systems.Society for Industrial and Applied Mathematics.doi:10.1137/1.9780898718881
Golub, G. H., & Van Loan, C. F. (2013).Matrix computations (4th ed.).Johns Hopkins University Press.doi:10.56021/9781421407944
See Also
ClasssparseQR and its methods.
ClassdgCMatrix.
Generic functionqr frombase,whose default methodqr.default “defines”the S3 classqr of dense QR factorizations.
Generic functionsexpand1 andexpand2,for constructing matrix factors from the result.
Generic functionsCholesky,BunchKaufman,Schur, andlu,for computing other factorizations.
Examples
showMethods("qr", inherited = FALSE)## Rank deficient: columns 3 {b2} and 6 {c3} are "extra"M <- as(cbind(a1 = 1, b1 = rep(c(1, 0), each = 3L), b2 = rep(c(0, 1), each = 3L), c1 = rep(c(1, 0, 0), 2L), c2 = rep(c(0, 1, 0), 2L), c3 = rep(c(0, 0, 1), 2L)), "CsparseMatrix")rownames(M) <- paste0("r", seq_len(nrow(M)))b <- 1:6eps <- .Machine$double.eps## .... [1] full rank ..................................................## ===> a least squares solution of A x = b exists## and is unique _in exact arithmetic_(A1 <- M[, -c(3L, 6L)])(qr.A1 <- qr(A1))stopifnot(exprs = { rankMatrix(A1) == ncol(A1) { d1 <- abs(diag(qr.A1@R)); sum(d1 < max(d1) * eps) == 0L } rcond(crossprod(A1)) >= eps all.equal(qr.coef(qr.A1, b), drop(solve(crossprod(A1), crossprod(A1, b)))) all.equal(qr.fitted(qr.A1, b) + qr.resid(qr.A1, b), b)})## .... [2] numerically rank deficient with full structural rank .......## ===> a least squares solution of A x = b does not## exist or is not unique _in exact arithmetic_(A2 <- M)(qr.A2 <- qr(A2))stopifnot(exprs = { rankMatrix(A2) == ncol(A2) - 2L { d2 <- abs(diag(qr.A2@R)); sum(d2 < max(d2) * eps) == 2L } rcond(crossprod(A2)) < eps ## 'qr.coef' computes unique least squares solution of "nearby" problem ## Z x = b for some full rank Z ~ A, currently without warning {FIXME} ! tryCatch({ qr.coef(qr.A2, b); TRUE }, condition = function(x) FALSE) all.equal(qr.fitted(qr.A2, b) + qr.resid(qr.A2, b), b)})## .... [3] numerically and structurally rank deficient ................## ===> factorization of _augmented_ matrix with## full structural rank proceeds as in [2]## NB: implementation details are subject to change; see (*) belowA3 <- MA3[, c(3L, 6L)] <- 0A3(qr.A3 <- qr(A3)) # with a warning ... "additional 2 row(s) of zeros"stopifnot(exprs = { ## sparseQR object preserves the unaugmented dimensions (*) dim(qr.A3 ) == dim(A3) dim(qr.A3@V) == dim(A3) + c(2L, 0L) dim(qr.A3@R) == dim(A3) + c(2L, 0L) ## The augmented matrix remains numerically rank deficient rankMatrix(A3) == ncol(A3) - 2L { d3 <- abs(diag(qr.A3@R)); sum(d3 < max(d3) * eps) == 2L } rcond(crossprod(A3)) < eps})## Auxiliary functions accept and return a vector or matrix## with dimensions corresponding to the unaugmented matrix (*),## in all cases with a warningqr.coef (qr.A3, b)qr.fitted(qr.A3, b)qr.resid (qr.A3, b)## .... [4] yet more examples ..........................................## By disabling column pivoting, one gets the "vanilla" factorization## A = Q~ R, where Q~ := P1' Q is orthogonal because P1 and Q are(qr.A1.pp <- qr(A1, order = 0L)) # partial pivotingae1 <- function(a, b, ...) all.equal(as(a, "matrix"), as(b, "matrix"), ...)ae2 <- function(a, b, ...) ae1(unname(a), unname(b), ...)stopifnot(exprs = { length(qr.A1 @q) == ncol(A1) length(qr.A1.pp@q) == 0L # indicating no column pivoting ae2(A1[, qr.A1@q + 1L], qr.Q(qr.A1 ) %*% qr.R(qr.A1 )) ae2(A1 , qr.Q(qr.A1.pp) %*% qr.R(qr.A1.pp))})Rank of a Matrix
Description
Compute ‘the’ matrix rank, a well-defined functional in theory(*),somewhat ambiguous in practice. We provide several methods, thedefault corresponding to Matlab's definition.
(*) The rank of an \times m matrixA,rk(A),is the maximal number of linearly independent columns (or rows); hencerk(A) \le min(n,m).
Usage
rankMatrix(x, tol = NULL, method = c("tolNorm2", "qr.R", "qrLINPACK", "qr", "useGrad", "maybeGrad"), sval = svd(x, 0, 0)$d, warn.t = TRUE, warn.qr = TRUE)qr2rankMatrix(qr, tol = NULL, isBqr = is.qr(qr), do.warn = TRUE)Arguments
x | numeric matrix, of dimension |
tol | nonnegative number specifying a (relative,“scalefree”) tolerance for testing of“practically zero” with specific meaning depending on |
method | a character string specifying the computational methodfor the rank, can be abbreviated:
|
sval | numeric vector of non-increasing singular values of |
warn.t | logical indicating if |
warn.qr | in the |
qr | anR object resulting from |
isBqr |
|
do.warn | logical; if true, warn about non-finite diagonalentries in the |
Details
qr2rankMatrix() is typically called fromrankMatrix() forthe"qr"*methods, but can be used directly - much moreefficiently in case theqr-decomposition is available anyway.
Value
Ifx is a matrix of all0 (or of zero dimension), the rankis zero; otherwise, typically a positive integer in1:min(dim(x))with attributes detailing the method used.
There are rare cases where the sparseQR decomposition“fails” in so far as the diagonal entries ofR, thed_i (see above), end with non-finite, typicallyNaNentries. Then, a warning is signalled (unlesswarn.qr /do.warn is not true) andNA (specifically,NA_integer_) is returned.
Note
For large sparse matricesx, unless you can specifysval yourself, currentlymethod = "qr" maybe the only feasible one, as the others needsval and callsvd() which currently coercesx to adenseMatrix which may be very slow or impossible,depending on the matrix dimensions.
Note that in the case of sparsex,method = "qr", allnon-strictly zero diagonal entriesd_i where counted, up toincludingMatrix version 1.1-0, i.e., that method implicitlyusedtol = 0, see also theset.seed(42) example below.
Author(s)
Martin Maechler; for the "*Grad" methods building onsuggestions by Ravi Varadhan.
See Also
Examples
rankMatrix(cbind(1, 0, 1:3)) # 2(meths <- eval(formals(rankMatrix)$method))## a "border" case:H12 <- Hilbert(12)rankMatrix(H12, tol = 1e-20) # 12; but 11 with default method & tol.sapply(meths, function(.m.) rankMatrix(H12, method = .m.))## tolNorm2 qr.R qrLINPACK qr useGrad maybeGrad## 11 11 12 12 11 11## The meaning of 'tol' for method="qrLINPACK" and *dense* x is not entirely "scale free"rMQL <- function(ex, M) rankMatrix(M, method="qrLINPACK",tol = 10^-ex)rMQR <- function(ex, M) rankMatrix(M, method="qr.R", tol = 10^-ex)sapply(5:15, rMQL, M = H12) # result is platform dependent## 7 7 8 10 10 11 11 11 12 12 12 {x86_64}sapply(5:15, rMQL, M = 1000 * H12) # not identical unfortunately## 7 7 8 10 11 11 12 12 12 12 12sapply(5:15, rMQR, M = H12)## 5 6 7 8 8 9 9 10 10 11 11sapply(5:15, rMQR, M = 1000 * H12) # the *same*## "sparse" case:M15 <- kronecker(diag(x=c(100,1,10)), Hilbert(5))sapply(meths, function(.m.) rankMatrix(M15, method = .m.))#--> all 15, but 'useGrad' has 14.sapply(meths, function(.m.) rankMatrix(M15, method = .m., tol = 1e-7)) # all 14## "large" sparsen <- 250000; p <- 33; nnz <- 10000L <- sparseMatrix(i = sample.int(n, nnz, replace=TRUE), j = sample.int(p, nnz, replace=TRUE), x = rnorm(nnz))(st1 <- system.time(r1 <- rankMatrix(L))) # warning+ ~1.5 sec (2013)(st2 <- system.time(r2 <- rankMatrix(L, method = "qr"))) # considerably faster!r1[[1]] == print(r2[[1]]) ## --> ( 33 TRUE )## another sparse-"qr" one, which ``failed'' till 2013-11-23:set.seed(42)f1 <- factor(sample(50, 1000, replace=TRUE))f2 <- factor(sample(50, 1000, replace=TRUE))f3 <- factor(sample(50, 1000, replace=TRUE))D <- t(do.call(rbind, lapply(list(f1,f2,f3), as, 'sparseMatrix')))dim(D); nnzero(D) ## 1000 x 150 // 3000 non-zeros (= 2%)stopifnot(rankMatrix(D, method='qr') == 148, rankMatrix(crossprod(D),method='qr') == 148)## zero matrix has rank 0 :stopifnot(sapply(meths, function(.m.) rankMatrix(matrix(0, 2, 2), method = .m.)) == 0)Estimate the Reciprocal Condition Number
Description
Estimate the reciprocal of the condition number of a matrix.
This is a generic function with several methods, as seen byshowMethods(rcond).
Usage
rcond(x, norm, ...)## S4 method for signature 'sparseMatrix,character'rcond(x, norm, useInv=FALSE, ...)Arguments
x | anR object that inherits from the |
norm | character string indicating the type of norm to be used inthe estimate. The default is |
useInv | logical (or This may be an efficient alternative (only) in situations where Note that theresult may differ depending on |
... | further arguments passed to or from other methods. |
Value
An estimate of the reciprocal condition number ofx.
BACKGROUND
The condition number of a regular (square) matrix is the product ofthenorm of the matrix and the norm of its inverse (orpseudo-inverse).
More generally, the condition number is defined (also fornon-square matricesA) as
\kappa(A) = \frac{\max_{\|v\| = 1} \|A v\|}{\min_{\|v\| = 1} \|A v\|}.
Wheneverx isnot a square matrix, in our methoddefinitions, this is typically computed viarcond(qr.R(qr(X)), ...)whereX isx ort(x).
The condition number takes on values between 1 and infinity,inclusive, and can be viewed as a factor by which errors in solvinglinear systems with this matrix as coefficient matrix could bemagnified.
rcond() computes thereciprocal condition number1/\kappa with values in[0,1] and can be viewed as ascaled measure of how close a matrix is to being rank deficient (aka“singular”).
Condition numbers are usually estimated, since exact computation iscostly in terms of floating-point operations. An (over) estimate ofreciprocal condition number is given, since by doing so overflow isavoided. Matrices are well-conditioned if the reciprocal conditionnumber is near 1 and ill-conditioned if it is near zero.
References
Golub, G., and Van Loan, C. F. (1989).Matrix Computations,2nd edition, Johns Hopkins, Baltimore.
See Also
norm,kappa() from packagebase computes anapproximate condition number of a“traditional” matrix, even non-square ones, with respect to thep=2 (Euclidean)norm.solve.
condest, a newerapproximate estimate ofthe (1-norm) condition number, particularly efficient for large sparsematrices.
Examples
x <- Matrix(rnorm(9), 3, 3)rcond(x)## typically "the same" (with more computational effort):1 / (norm(x) * norm(solve(x)))rcond(Hilbert(9)) # should be about 9.1e-13## For non-square matrices:rcond(x1 <- cbind(1,1:10))# 0.05278rcond(x2 <- cbind(x1, 2:11))# practically 0, since x2 does not have full rank## sparse(S1 <- Matrix(rbind(0:1,0, diag(3:-2))))rcond(S1)m1 <- as(S1, "denseMatrix")all.equal(rcond(S1), rcond(m1))## wide and sparsercond(Matrix(cbind(0, diag(2:-1))))## Large sparse example ----------m <- Matrix(c(3,0:2), 2,2)M <- bdiag(kronecker(Diagonal(2), m), kronecker(m,m))36*(iM <- solve(M)) # still sparseMM <- kronecker(Diagonal(10), kronecker(Diagonal(5),kronecker(m,M)))dim(M3 <- kronecker(bdiag(M,M),MM)) # 12'800 ^ 2if(interactive()) ## takes about 2 seconds if you have >= 8 GB RAM system.time(r <- rcond(M3))## whereas this is *fast* even though it computes solve(M3)system.time(r. <- rcond(M3, useInv=TRUE))if(interactive()) ## the values are not the same c(r, r.) # 0.05555 0.013888## for all 4 norms available for sparseMatrix :cbind(rr <- sapply(c("1","I","F","M"), function(N) rcond(M3, norm=N, useInv=TRUE)))Replicate Vectors into 'abIndex' Result
Description
rep2abI(x, times) conceptually computesrep.int(x, times) but with anabIndex class result.
Usage
rep2abI(x, times)Arguments
x | numeric vector |
times | integer (valued) scalar: the number of repetitions |
Value
See Also
rep.int(), the base function;abIseq,abIndex.
Examples
(ab <- rep2abI(2:7, 4))stopifnot(identical(as(ab, "numeric"), rep(2:7, 4)))Class "rleDiff" of rle(diff(.)) Stored Vectors
Description
Class"rleDiff" is for compactly storing long vectorswhich mainly consist oflinear stretches. For such a vectorx,diff(x) consists ofconstant stretchesand is hence well compressable viarle().
Objects from the Class
Objects can be created by calls of the formnew("rleDiff", ...).
Currently experimental, see below.
Slots
first:A single number (of class
"numLike",a class union of"numeric"and"logical").rle:Object of class
"rle", basically alistwith components"lengths"and"values", seerle(). As this is used toencode potentially huge index vectors,lengthsmay be oftypedoublehere.
Methods
There is a simpleshow method only.
Note
This is currently anexperimental auxiliary classfor the classabIndex, see there.
See Also
Examples
showClass("rleDiff")ab <- c(abIseq(2, 100), abIseq(20, -2))ab@rleD # is "rleDiff"Random Sparse Matrix
Description
Generate a random sparse matrix efficiently. The default has roundedgaussian non-zero entries, andrand.x = NULL generates randompattern matrices, i.e. inheriting fromnsparseMatrix.
Usage
rsparsematrix(nrow, ncol, density, nnz = round(density * maxE), symmetric = FALSE, rand.x = function(n) signif(rnorm(n), 2), ...)Arguments
nrow,ncol | number of rows and columns, i.e., the matrixdimension ( |
density | optional number in |
nnz | number of non-zero entries, for a sparse matrix typicallyconsiderably smaller than |
symmetric | logical indicating if result should be a matrix ofclass |
rand.x |
|
... | optionally further arguments passed to |
Details
The algorithm first samples “encoded”(i,j)s withoutreplacement, via one dimensional indices, if notsymmetricsample.int(nrow*ncol, nnz), then—ifrand.x isnotNULL—getsx <- rand.x(nnz) and callssparseMatrix(i=i, j=j, x=x, ..). Whenrand.x=NULL,sparseMatrix(i=i, j=j, ..) willreturn a pattern matrix (i.e., inheriting fromnsparseMatrix).
Value
asparseMatrix, sayM of dimension (nrow,ncol), i.e., withdim(M) == c(nrow, ncol), ifsymmetricis not true, withnzM <-nnzero(M) fulfillingnzM <= nnz and typically,nzM == nnz.
Author(s)
Martin Maechler
Examples
set.seed(17)# to be reproducibleM <- rsparsematrix(8, 12, nnz = 30) # small example, not very sparseMM1 <- rsparsematrix(1000, 20, nnz = 123, rand.x = runif)summary(M1)## a random *symmetric* Matrix(S9 <- rsparsematrix(9, 9, nnz = 10, symmetric=TRUE)) # dsCMatrixnnzero(S9)# ~ 20: as 'nnz' only counts one "triangle"## a random patter*n* aka boolean Matrix (no 'x' slot):(n7 <- rsparsematrix(5, 12, nnz = 10, rand.x = NULL))## a [T]riplet representation sparseMatrix:T2 <- rsparsematrix(40, 12, nnz = 99, repr = "T")head(T2)Methods in PackageMatrix for Functionsolve
Description
Methods for generic functionsolve for solvinglinear systems of equations,i.e., forX inA X = B,whereA is a square matrix andX andB are matriceswith dimensions consistent withA.
Usage
solve(a, b, ...)## S4 method for signature 'dgeMatrix,ANY'solve(a, b, tol = .Machine$double.eps, ...)## S4 method for signature 'dgCMatrix,missing'solve(a, b, sparse = TRUE, ...)## S4 method for signature 'dgCMatrix,matrix'solve(a, b, sparse = FALSE, ...)## S4 method for signature 'dgCMatrix,denseMatrix'solve(a, b, sparse = FALSE, ...)## S4 method for signature 'dgCMatrix,sparseMatrix'solve(a, b, sparse = TRUE, ...)## S4 method for signature 'denseLU,dgeMatrix'solve(a, b, ...)## S4 method for signature 'BunchKaufman,dgeMatrix'solve(a, b, ...)## S4 method for signature 'Cholesky,dgeMatrix'solve(a, b, ...)## S4 method for signature 'sparseLU,dgCMatrix'solve(a, b, tol = .Machine$double.eps, ...)## S4 method for signature 'sparseQR,dgCMatrix'solve(a, b, ...)## S4 method for signature 'CHMfactor,dgCMatrix'solve(a, b, system = c("A", "LDLt", "LD", "DLt", "L", "Lt", "D", "P", "Pt"), ...)Arguments
a | afinite square matrix or |
b | a vector, |
tol | a non-negative number. For |
sparse | a logical indicating if the result should be formallysparse, i.e., if the result should inherit from virtual class |
system | a string specifying a linear system to be solved.Only methods for |
... | further arguments passed to or from methods. |
Details
Methods for general and symmetric matricesa compute atriangular factorization (LU, Bunch-Kaufman, or Cholesky)and call the method for the corresponding factorization class.The factorization is sparse ifa is. Methods for sparse,symmetric matricesa attempt a Cholesky factorizationand perform an LU factorization only if that fails (typicallybecausea is not positive definite).
Triangular, diagonal, and permutation matrices do not requirefactorization (they are already “factors”), hence methodsfor those are implemented directly. For triangulara,solutions are obtained by forward or backward substitution;for diagonala, they are obtained by scaling the rowsofb; and for permutationsa, they are obtainedby permuting the rows ofb.
Methods for densea are built on 14 LAPACK routines:classd..Matrix, where..=(ge|tr|tp|sy|sp|po|pp),uses routinesd..tri andd..trs for missingand non-missingb, respectively. A corollary is thatthese methods always give a dense result.
Methods for sparsea are built on CXSparse routinescs_lsolve,cs_usolve, andcs_spsolve andCHOLMOD routinescholmod_solve andcholmod_spsolve.By default, these methods give a vector result ifbis a vector, a sparse matrix result ifb is missingor a sparse matrix, and a dense matrix result ifbis a dense matrix. One can override this behaviour by settingthesparse argument, where available, but that shouldbe done with care. Note that a sparse result may be sparse onlyin the formal sense and not at all in the mathematical sense,depending on the nonzero patterns ofa andb.Furthermore, whereas dense results are fully preallocated,sparse results must be “grown” in a loop over the columnsofb.
Methods fora of classsparseQRare simple wrappers aroundqr.coef, giving theleast squares solution in overdetermined cases.
Methods fora inheriting fromCHMfactorcan solve systems other than the default oneA X = B.The correspondence between itssystem argument the systemactually solved is outlined in the table below.SeeCHMfactor-class for a definition of notation.
system | isLDL(a)=TRUE | isLDL(a)=FALSE |
"A" | A X = B | A X = B |
"LDLt" | L_{1} D L_{1}' X = B | L L' X = B |
"LD" | L_{1} D X = B | L X = B |
"DLt" | D L_{1}' X = B | L' X = B |
"L" | L_{1} X = B | L X = B |
"Lt" | L_{1}' X = B | L' X = B |
"D" | D X = B | X = B |
"P" | X = P_{1} B | X = P_{1} B |
"Pt" | X = P_{1}' B | X = P_{1}' B |
See Also
Virtual classMatrixFactorization and itssubclasses.
Generic functionsCholesky,BunchKaufman,Schur,lu, andqr forcomputing factorizations.
Generic functionsolve frombase.
Functionqr.coef frombase for computingleast squares solutions of overdetermined linear systems.
Examples
## A close to symmetric example with "quite sparse" inverse:n1 <- 7; n2 <- 3dd <- data.frame(a = gl(n1,n2), b = gl(n2,1,n1*n2))# balanced 2-wayX <- sparse.model.matrix(~ -1+ a + b, dd)# no intercept --> even sparserXXt <- 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) # FALSEimage(drop0(skewpart(a)))image(ia0 <- solve(a, tol = 0)) # 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* errorif(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=FALSE)stopifnot(all.equal(as(iad,"denseMatrix"), ias, 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)) )Sparse Matrix Constructor From Triplet
Description
User friendly construction of a sparse matrix (inheriting from classTsparseMatrix) from the triplet representation.
This is much less flexible thansparseMatrix() and hencesomewhatdeprecated.
Usage
spMatrix(nrow, ncol, i = integer(0L), j = integer(0L), x = double(0L))Arguments
nrow,ncol | integers specifying the desired number of rows andcolumns. |
i,j | integer vectors of the same length specifying the locationsof the non-zero (or non- |
x | atomic vector of the same length as |
Value
A sparse matrix in triplet form, as anR object inheriting from bothTsparseMatrix andgeneralMatrix.
The matrixM will haveM[i[k], j[k]] == x[k], fork = 1,2,\ldots, n, wheren = length(i) andM[ i', j' ] == 0 for all other pairs(i',j').
See Also
Matrix(*, sparse=TRUE) for the more usualconstructor of such matrices. Then,sparseMatrixis more general and flexible thanspMatrix() and by defaultreturns aCsparseMatrix which is often slightlymore desirable. Further,bdiag andDiagonal for (block-)diagonal matrix constructors.
ConsiderTsparseMatrix and similar classdefinition help files.
Examples
## simple exampleA <- spMatrix(10,20, i = c(1,3:8), j = c(2,9,6:10), x = 7 * (1:7))A # a "dgTMatrix"summary(A)str(A) # note that *internally* 0-based indices (i,j) are usedL <- spMatrix(9, 30, i = rep(1:9, 3), 1:27, (1:27) %% 4 != 1)L # an "lgTMatrix"## A simplified predecessor of Matrix' rsparsematrix() function : rSpMatrix <- function(nrow, ncol, nnz, rand.x = function(n) round(rnorm(nnz), 2)) { ## Purpose: random sparse matrix ## -------------------------------------------------------------- ## Arguments: (nrow,ncol): dimension ## nnz : number of non-zero entries ## rand.x: random number generator for 'x' slot ## -------------------------------------------------------------- ## Author: Martin Maechler, Date: 14.-16. May 2007 stopifnot((nnz <- as.integer(nnz)) >= 0, nrow >= 0, ncol >= 0, nnz <= nrow * ncol) spMatrix(nrow, ncol, i = sample(nrow, nnz, replace = TRUE), j = sample(ncol, nnz, replace = TRUE), x = rand.x(nnz)) } M1 <- rSpMatrix(100000, 20, nnz = 200) summary(M1)Construct Sparse Design / Model Matrices
Description
Construct a sparse model or “design” matrix,from a formula and data frame (sparse.model.matrix) or a singlefactor (fac2sparse).
Thefac2[Ss]parse() functions are utilities, also usedinternally in the principal user level functionsparse.model.matrix().
Usage
sparse.model.matrix(object, data = environment(object), contrasts.arg = NULL, xlev = NULL, transpose = FALSE, drop.unused.levels = FALSE, row.names = TRUE, sep = "", verbose = FALSE, ...)fac2sparse(from, to = c("d", "l", "n"), drop.unused.levels = TRUE, repr = c("C", "R", "T"), giveCsparse)fac2Sparse(from, to = c("d", "l", "n"), drop.unused.levels = TRUE, repr = c("C", "R", "T"), giveCsparse, factorPatt12, contrasts.arg = NULL)Arguments
object | an object of an appropriate class. For the defaultmethod, a model formula or terms object. |
data | a data frame created with |
contrasts.arg |
|
xlev | to be used as argument of |
transpose | logical indicating if thetranspose should bereturned; if the transposed is used anyway, setting |
drop.unused.levels | should factors have unused levels dropped?The default for |
row.names | logical indicating if row names should be used. |
sep |
|
verbose | logical or integer indicating if (and how much)progress output should be printed. |
... | further arguments passed to or from other methods. |
from | (for |
to | a character indicating the “kind” of sparse matrix tobe returned. The default, |
giveCsparse | deprecated, replaced with |
repr |
|
factorPatt12 | logical vector, say |
Value
a sparse matrix, extendingCsparseMatrix (forfac2sparse() ifrepr = "C" as per default; aTsparseMatrix orRsparseMatrix, otherwise).
Forfac2Sparse(), alist of length two, bothcomponents with the corresponding transposed model matrix, where thecorrespondingfactorPatt12 is true.
fac2sparse(), the basic workhorse ofsparse.model.matrix(), returns thetranspose(t) of the model matrix.
Note
model.Matrix(sparse = TRUE) from packageMatrixModelsmay be nowadays be preferable tosparse.model.matrix,asmodel.Matrix returns an object of classmodelMatrixwith additional slotsassign andcontrasts relating tothe model variables.
Author(s)
Doug Bates and Martin Maechler, with initial suggestions from TimHesterberg.
See Also
model.matrix in packagestats, part of baseR.
model.Matrix in packageMatrixModels; see ‘Note’.
as(f, "sparseMatrix") (seecoerce(from = "factor", ..)in the class docsparseMatrix) produces thetransposed sparse model matrix for a single factorf(andno contrasts).
Examples
dd <- data.frame(a = gl(3,4), b = gl(4,1,12))# balanced 2-wayoptions("contrasts") # the default: "contr.treatment"sparse.model.matrix(~ a + b, dd)sparse.model.matrix(~ -1+ a + b, dd)# no intercept --> even sparsersparse.model.matrix(~ a + b, dd, contrasts = list(a="contr.sum"))sparse.model.matrix(~ a + b, dd, contrasts = list(b="contr.SAS"))## Sparse method is equivalent to the traditional one :stopifnot(all(sparse.model.matrix(~ a + b, dd) == Matrix(model.matrix(~ a + b, dd), sparse=TRUE)), all(sparse.model.matrix(~0 + a + b, dd) == Matrix(model.matrix(~0 + a + b, dd), sparse=TRUE)))(ff <- gl(3,4,, c("X","Y", "Z")))fac2sparse(ff) # 3 x 12 sparse Matrix of class "dgCMatrix"#### X 1 1 1 1 . . . . . . . .## Y . . . . 1 1 1 1 . . . .## Z . . . . . . . . 1 1 1 1## can also be computed via sparse.model.matrix():f30 <- gl(3,0 )f12 <- gl(3,0, 12)stopifnot( all.equal(t( fac2sparse(ff) ), sparse.model.matrix(~ 0+ff), tolerance = 0, check.attributes=FALSE), is(M <- fac2sparse(f30, drop= TRUE),"CsparseMatrix"), dim(M) == c(0, 0), is(M <- fac2sparse(f30, drop=FALSE),"CsparseMatrix"), dim(M) == c(3, 0), is(M <- fac2sparse(f12, drop= TRUE),"CsparseMatrix"), dim(M) == c(0,12), is(M <- fac2sparse(f12, drop=FALSE),"CsparseMatrix"), dim(M) == c(3,12) )Sparse LU Factorizations
Description
sparseLU is the class of sparse, row- and column-pivotedLU factorizations ofn \times n real matricesA,having the general form
P_{1} A P_{2} = L U
or (equivalently)
A = P_{1}' L U P_{2}'
whereP_{1} andP_{2} are permutation matrices,L is a unit lower triangular matrix, andU is an upper triangular matrix.
Slots
Dim,Dimnamesinherited from virtual class
MatrixFactorization.Lan object of class
dtCMatrix,the unit lower triangularLfactor.Uan object of class
dtCMatrix,the upper triangularUfactor.p,q0-based integer vectors of length
Dim[1],specifying the permutations applied to the rows and columns ofthe factorized matrix.qof length 0 is valid andequivalent to the identity permutation, implying no column pivoting.UsingR syntax, the matrixP_{1} A P_{2}is preciselyA[p+1, q+1](A[p+1, ]whenqhas length 0).
Extends
ClassLU, directly.ClassMatrixFactorization, by classLU, distance 2.
Instantiation
Objects can be generated directly by calls of the formnew("sparseLU", ...), but they are more typically obtainedas the value oflu(x) forx inheriting fromsparseMatrix (oftendgCMatrix).
Methods
determinantsignature(from = "sparseLU", logarithm = "logical"):computes the determinant of the factorized matrixAor its logarithm.expandsignature(x = "sparseLU"):seeexpand-methods.expand1signature(x = "sparseLU"):seeexpand1-methods.expand2signature(x = "sparseLU"):seeexpand2-methods.solvesignature(a = "sparseLU", b = .):seesolve-methods.
References
Davis, T. A. (2006).Direct methods for sparse linear systems.Society for Industrial and Applied Mathematics.doi:10.1137/1.9780898718881
Golub, G. H., & Van Loan, C. F. (2013).Matrix computations (4th ed.).Johns Hopkins University Press.doi:10.56021/9781421407944
See Also
ClassdenseLU for dense LU factorizations.
ClassdgCMatrix.
Generic functionslu,expand1 andexpand2.
Examples
showClass("sparseLU")set.seed(2)A <- as(readMM(system.file("external", "pores_1.mtx", package = "Matrix")), "CsparseMatrix")(n <- A@Dim[1L])## With dimnames, to see that they are propagated :dimnames(A) <- dn <- list(paste0("r", seq_len(n)), paste0("c", seq_len(n)))(lu.A <- lu(A))str(e.lu.A <- expand2(lu.A), max.level = 2L)ae1 <- function(a, b, ...) all.equal(as(a, "matrix"), as(b, "matrix"), ...)ae2 <- function(a, b, ...) ae1(unname(a), unname(b), ...)## A ~ P1' L U P2' in floating pointstopifnot(exprs = { identical(names(e.lu.A), c("P1.", "L", "U", "P2.")) identical(e.lu.A[["P1."]], new("pMatrix", Dim = c(n, n), Dimnames = c(dn[1L], list(NULL)), margin = 1L, perm = invertPerm(lu.A@p, 0L, 1L))) identical(e.lu.A[["P2."]], new("pMatrix", Dim = c(n, n), Dimnames = c(list(NULL), dn[2L]), margin = 2L, perm = invertPerm(lu.A@q, 0L, 1L))) identical(e.lu.A[["L"]], lu.A@L) identical(e.lu.A[["U"]], lu.A@U) ae1(A, with(e.lu.A, P1. %*% L %*% U %*% P2.)) ae2(A[lu.A@p + 1L, lu.A@q + 1L], with(e.lu.A, L %*% U))})## Factorization handled as factorized matrixb <- rnorm(n)stopifnot(identical(det(A), det(lu.A)), identical(solve(A, b), solve(lu.A, b)))General Sparse Matrix Construction from Nonzero Entries
Description
User-friendly construction of sparse matrices (inheriting fromvirtualclassCsparseMatrix,RsparseMatrix, orTsparseMatrix)from the positions and values of their nonzero entries.
This interface is recommended over direct construction viacalls such asnew("..[CRT]Matrix", ...).
Usage
sparseMatrix(i, j, p, x, dims, dimnames, symmetric = FALSE, triangular = FALSE, index1 = TRUE, repr = c("C", "R", "T"), giveCsparse, check = TRUE, use.last.ij = FALSE)Arguments
i,j | integer vectors of equal length specifying the positions(row and column indices) of the nonzero (or non- |
p | integer vector of pointers, one for each column (or row),to the initial (zero-based) index of elements in the column (or row).Exactly one of |
x | optional, typically nonzero values for the matrix entries.If specified, then the length must equal that of |
dims | optional length-2 integer vector of matrix dimensions.If missing, then |
dimnames | optional list of |
symmetric | logical indicating if the resulting matrix shouldbe symmetric. In that case, |
triangular | logical indicating if the resulting matrix shouldbe triangular. In that case, |
index1 | logical. If |
repr |
|
giveCsparse | (deprecated, replaced by |
check | logical indicating whether to check that the result isformally valid before returning. Do not set to |
use.last.ij | logical indicating if, in the case of repeated(duplicated) pairs |
Details
Exactly one of the argumentsi,j andp must bemissing.
In typical usage,p is missing,i andj arevectors of positive integers andx is a numeric vector. Thesethree vectors, which must have the same length, form the tripletrepresentation of the sparse matrix.
Ifi orj is missing thenp must be anon-decreasing integer vector whose first element is zero. Itprovides the compressed, or “pointer” representation of the rowor column indices, whichever is missing. The expanded form ofp,rep(seq_along(dp),dp) wheredp <- diff(p), is used asthe (1-based) row or column indices.
You cannot set bothsingular andtriangular to true;rather useDiagonal() (or its alternatives, see there).
The values ofi,j,p andindex1 are usedto create 1-based index vectorsi andj from which aTsparseMatrix is constructed, with numericalvalues given byx, if non-missing. Note that in that case,when some pairs(i_k,j_k) are repeated (aka“duplicated”), the correspondingx_k areadded, inconsistency with the definition of theTsparseMatrix class, unlessuse.last.ijis set to true.
By default, whenrepr = "C", theCsparseMatrixderived from this triplet form is returned, whererepr = "R" nowallows to directly get anRsparseMatrix andrepr = "T" leaves the result asTsparseMatrix.
The reason for returning aCsparseMatrix objectinstead of the triplet format by default is that the compressed columnform is easier to work with when performing matrix operations. Inparticular, if there are no zeros inx then aCsparseMatrix is a unique representation of thesparse matrix.
Value
A sparse matrix, by default in compressed sparse column format and(formally) without symmetric or triangular structure, i.e.,by default inheriting from bothCsparseMatrixandgeneralMatrix.
Note
Youdo need to useindex1 = FALSE (or add+ 1toi andj) if you want use the 0-basedi (andj) slots from existing sparse matrices.
See Also
Matrix(*, sparse=TRUE) for the constructor ofsuch matrices from adense matrix. That is easier in smallsample, but much less efficient (or impossible) for large matrices,where something likesparseMatrix() is needed.Furtherbdiag andDiagonal for (block-)diagonal andbandSparse for banded sparse matrix constructors.
Random sparse matrices viarsparsematrix().
The standardRxtabs(*, sparse=TRUE), for sparse tablesandsparse.model.matrix() for building sparse modelmatrices.
ConsiderCsparseMatrix and similar classdefinition help files.
Examples
## simple examplei <- c(1,3:8); j <- c(2,9,6:10); x <- 7 * (1:7)(A <- sparseMatrix(i, j, x = x)) ## 8 x 10 "dgCMatrix"summary(A)str(A) # note that *internally* 0-based row indices are used(sA <- sparseMatrix(i, j, x = x, symmetric = TRUE)) ## 10 x 10 "dsCMatrix"(tA <- sparseMatrix(i, j, x = x, triangular= TRUE)) ## 10 x 10 "dtCMatrix"stopifnot( all(sA == tA + t(tA)) , identical(sA, as(tA + t(tA), "symmetricMatrix")))## dims can be larger than the maximum row or column indices(AA <- sparseMatrix(c(1,3:8), c(2,9,6:10), x = 7 * (1:7), dims = c(10,20)))summary(AA)## i, j and x can be in an arbitrary order, as long as they are consistentset.seed(1); (perm <- sample(1:7))(A1 <- sparseMatrix(i[perm], j[perm], x = x[perm]))stopifnot(identical(A, A1))## The slots are 0-index based, sotry( sparseMatrix(i=A@i, p=A@p, x= seq_along(A@x)) )## fails and you should say so: 1-indexing is FALSE: sparseMatrix(i=A@i, p=A@p, x= seq_along(A@x), index1 = FALSE)## the (i,j) pairs can be repeated, in which case the x's are summed(args <- data.frame(i = c(i, 1), j = c(j, 2), x = c(x, 2)))(Aa <- do.call(sparseMatrix, args))## explicitly ask for elimination of such duplicates, so## that the last one is used:(A. <- do.call(sparseMatrix, c(args, list(use.last.ij = TRUE))))stopifnot(Aa[1,2] == 9, # 2+7 == 9 A.[1,2] == 2) # 2 was *after* 7## for a pattern matrix, of course there is no "summing":(nA <- do.call(sparseMatrix, args[c("i","j")]))dn <- list(LETTERS[1:3], letters[1:5])## pointer vectors can be used, and the (i,x) slots are sorted if necessary:m <- sparseMatrix(i = c(3,1, 3:2, 2:1), p= c(0:2, 4,4,6), x = 1:6, dimnames = dn)mstr(m)stopifnot(identical(dimnames(m), dn))sparseMatrix(x = 2.72, i=1:3, j=2:4) # recycling xsparseMatrix(x = TRUE, i=1:3, j=2:4) # recycling x, |--> "lgCMatrix"## no 'x' --> patter*n* matrix:(n <- sparseMatrix(i=1:6, j=rev(2:7)))# -> ngCMatrix## an empty sparse matrix:(e <- sparseMatrix(dims = c(4,6), i={}, j={}))## a symmetric one:(sy <- sparseMatrix(i= c(2,4,3:5), j= c(4,7:5,5), x = 1:5, dims = c(7,7), symmetric=TRUE))stopifnot(isSymmetric(sy), identical(sy, ## switch i <-> j {and transpose } t( sparseMatrix(j= c(2,4,3:5), i= c(4,7:5,5), x = 1:5, dims = c(7,7), symmetric=TRUE))))## rsparsematrix() calls sparseMatrix() :M1 <- rsparsematrix(1000, 20, nnz = 200)summary(M1)## pointers example in converting from other sparse matrix representations.if(requireNamespace("SparseM") && packageVersion("SparseM") >= "0.87" && nzchar(dfil <- system.file("extdata", "rua_32_ax.rua", package = "SparseM"))) { X <- SparseM::model.matrix(SparseM::read.matrix.hb(dfil)) XX <- sparseMatrix(j = X@ja, p = X@ia - 1L, x = X@ra, dims = X@dimension) validObject(XX) ## Alternatively, and even more user friendly : X. <- as(X, "Matrix") # or also X2 <- as(X, "sparseMatrix") stopifnot(identical(XX, X.), identical(X., X2))}Virtual Class "sparseMatrix" — Mother of Sparse Matrices
Description
Virtual Mother Class of All Sparse Matrices
Slots
Dim:Object of class
"integer"- the dimensionsof the matrix - must be an integer vector with exactly twonon-negative values.Dimnames:a list of length two - inherited from class
Matrix, seeMatrix.
Extends
Class"Matrix", directly.
Methods
- show
(object = "sparseMatrix"): Theshowmethod for sparse matrices prints“structural” zeroes as"."usingprintSpMatrix()which allows further customization.signature(x = "sparseMatrix"), ....
Theprintmethod for sparse matrices by default is thesame asshow()but can be called with extra optionalarguments, seeprintSpMatrix().- format
signature(x = "sparseMatrix"), ....
Theformatmethod for sparse matrices, seeformatSpMatrix()for details such as the extraoptional arguments.- summary
(object = "sparseMatrix", uniqT=FALSE): Returnsan object of S3 class"sparseSummary"which is basically adata.framewith columns(i,j,x)(or just(i,j)fornsparseMatrixclass objects)with the stored (typically non-zero) entries. Theprintmethod resembles Matlab's way of printingsparse matrices, and also the MatrixMarket format, seewriteMM.- cbind2
(x = *, y = *): several methods for bindingmatrices together, column-wise, see the basiccbindandrbindfunctions.
Note that the result will typically be sparse, even when oneargument is dense and larger than the sparse one.- rbind2
(x = *, y = *): binding matrices togetherrow-wise, seecbind2above.- determinant
(x = "sparseMatrix", logarithm=TRUE):determinant()methods for sparse matrices typicallywork viaCholeskyorludecompositions.- diag
(x = "sparseMatrix"): extracts the diagonal of asparse matrix.- dim<-
signature(x = "sparseMatrix", value = "ANY"):allows toreshape a sparse matrix to a sparse matrix withthe same entries but different dimensions.valuemust be oflength two and fulfillprod(value) == prod(dim(x)).- coerce
signature(from = "factor", to = "sparseMatrix"):Coercion of a factor to"sparseMatrix"produces the matrixof indicatorrows stored as an object of class"dgCMatrix". To obtain columns representing the interactionof the factor and a numeric covariate, replace the"x"slotof the result by the numeric covariate then take the transpose.Missing values (NA) from the factor are translatedto columns of all0s.
See alsocolSums,norm,... for methods with separate help pages.
Note
In method selection for multiplication operations (i.e.%*%and the two-argument form ofcrossprod)the sparseMatrix class takes precedence in the sense that if oneoperand is a sparse matrix and the other is any type of dense matrixthen the dense matrix is coerced to adgeMatrix and theappropriate sparse matrix method is used.
See Also
sparseMatrix, and its references, such asxtabs(*, sparse=TRUE), orsparse.model.matrix(),for constructing sparse matrices.
T2graph for conversion of"graph" objects(packagegraph) to and from sparse matrices.
Examples
showClass("sparseMatrix") ## and look at the help() of its subclassesM <- Matrix(0, 10000, 100)M[1,1] <- M[2,3] <- 3.14M ## show(.) method suppresses printing of the majority of rowsdata(CAex, package = "Matrix")dim(CAex) # 72 x 72 matrixdeterminant(CAex) # works via sparse lu(.)## factor -> t( <sparse design matrix> ) :(fact <- gl(5, 3, 30, labels = LETTERS[1:5]))(Xt <- as(fact, "sparseMatrix")) # indicator rows## missing values --> all-0 columns:f.mis <- facti.mis <- c(3:5, 17)is.na(f.mis) <- i.misXt != (X. <- as(f.mis, "sparseMatrix")) # differ only in columns 3:5,17stopifnot(all(X.[,i.mis] == 0), all(Xt[,-i.mis] == X.[,-i.mis]))Sparse QR Factorizations
Description
sparseQR is the class of sparse, row- and column-pivotedQR factorizations ofm \times n (m \ge n)real matrices, having the general form
P_1 A P_2 = Q R = \begin{bmatrix} Q_1 & Q_2 \end{bmatrix} \begin{bmatrix} R_1 \\ 0 \end{bmatrix} = Q_1 R_1
or (equivalently)
A = P_1' Q R P_2' = P_1' \begin{bmatrix} Q_1 & Q_2 \end{bmatrix} \begin{bmatrix} R_1 \\ 0 \end{bmatrix} P_2' = P_1' Q_1 R_1 P_2'
whereP_1 andP_2 are permutation matrices,Q = \prod_{j = 1}^{n} H_jis anm \times m orthogonal matrix(Q_1 contains the firstn column vectors)equal to the product ofn Householder matricesH_j, andR is anm \times n upper trapezoidal matrix(R_1 contains the firstn row vectors and isuppertriangular).
Usage
qrR(qr, complete = FALSE, backPermute = TRUE, row.names = TRUE)Arguments
qr | an object of class |
complete | a logical indicating if |
backPermute | a logical indicating if |
row.names | a logical indicating if |
Details
The method forqr.Q does not returnQ but rather the(also orthogonal) productP_1' Q. This behaviouris algebraically consistent with thebase implementation(seeqr), which can be seen by noting thatqr.default inbase does not pivot rows, constrainingP_1 to be an identity matrix. It follows thatqr.Q(qr.default(x)) also returnsP_1' Q.
Similarly, the methods forqr.qy andqr.qty multiplyon the left byP_1' Q andQ' P_1rather thanQ andQ'.
It is wrong to expect the values ofqr.Q (orqr.R,qr.qy,qr.qty) computed from “equivalent”sparse and dense factorizations(say,qr(x) andqr(as(x, "matrix")) forxof classdgCMatrix) to compare equal.The underlying factorization algorithms are quite different,notably as they employ different pivoting strategies,and in general the factorization is not unique even for fixedP_1 andP_2.
On the other hand, the values ofqr.X,qr.coef,qr.fitted, andqr.resid are well-defined, andin those cases the sparse and dense computationsshouldcompare equal (within some tolerance).
The method forqr.R is a simple wrapper aroundqrR,but not back-permuting by default and never giving row names.It did not supportbackPermute = TRUE untilMatrix1.6-0, hence code needing the back-permuted result shouldcallqrR ifMatrix>= 1.6-0 is not known.
Slots
Dim,Dimnamesinherited from virtual class
MatrixFactorization.betaa numeric vector of length
Dim[2],used to construct Householder matrices; seeVbelow.Van object of class
dgCMatrixwithDim[2]columns. The number of rowsnrow(V)is at leastDim[1]and at mostDim[1]+Dim[2].Vis lower trapezoidal, and its column vectors generate theHouseholder matricesH_jthat compose the orthogonalQfactor. Specifically,H_jis constructed asdiag(Dim[1]) - beta[j] * tcrossprod(V[, j]).Ran object of class
dgCMatrixwithnrow(V)rows andDim[2]columns.Ris the upper trapezoidalRfactor.p,q0-based integer vectors of length
nrow(V)andDim[2], respectively,specifying the permutations applied to the rows and columns ofthe factorized matrix.qof length 0 is valid andequivalent to the identity permutation, implying no column pivoting.UsingR syntax, the matrixP_1 A P_2is preciselyA[p+1, q+1](A[p+1, ]whenqhas length 0).
Extends
ClassQR, directly.ClassMatrixFactorization, by classQR, distance 2.
Instantiation
Objects can be generated directly by calls of the formnew("sparseQR", ...), but they are more typically obtainedas the value ofqr(x) forx inheriting fromsparseMatrix (oftendgCMatrix).
Methods
determinantsignature(from = "sparseQR", logarithm = "logical"):computes the determinant of the factorized matrixAor its logarithm.expand1signature(x = "sparseQR"):seeexpand1-methods.expand2signature(x = "sparseQR"):seeexpand2-methods.qr.Qsignature(qr = "sparseQR"):returns as adgeMatrixeitherP_1' QorP_1' Q_1,depending on optional argumentcomplete. The defaultisFALSE, indicatingP_1' Q_1.qr.Rsignature(qr = "sparseQR"):qrRreturnsR,R_1,R P2', orR_1 P2',depending on optional argumentscompleteandbackPermute. The default in both cases isFALSE,indicatingR_1, for compatibility withbase. The class of the result in that case isdtCMatrix. In the other three cases,it isdgCMatrix.qr.Xsignature(qr = "sparseQR"):returnsAas adgeMatrix,by default. Ifm > nand optional argumentncolis greater thann, then the resultis augmented withP_1' Q J, whereJis composed of columns(n+1)throughncolof them \times midentity matrix.qr.coefsignature(qr = "sparseQR", y = .):returns as adgeMatrixor vectorthe result of multiplyingyon the left byP_2 R_1^{-1} Q_1' P_1.qr.fittedsignature(qr = "sparseQR", y = .):returns as adgeMatrixor vectorthe result of multiplyingyon the left byP_1' Q_1 Q_1' P_1.qr.residsignature(qr = "sparseQR", y = .):returns as adgeMatrixor vectorthe result of multiplyingyon the left byP_1' Q_2 Q_2' P_1.qr.qtysignature(qr = "sparseQR", y = .):returns as adgeMatrixor vectorthe result of multiplyingyon the left byQ' P_1.qr.qysignature(qr = "sparseQR", y = .):returns as adgeMatrixor vectorthe result of multiplyingyon the left byP_1' Q.solvesignature(a = "sparseQR", b = .):seesolve-methods.
References
Davis, T. A. (2006).Direct methods for sparse linear systems.Society for Industrial and Applied Mathematics.doi:10.1137/1.9780898718881
Golub, G. H., & Van Loan, C. F. (2013).Matrix computations (4th ed.).Johns Hopkins University Press.doi:10.56021/9781421407944
See Also
ClassdgCMatrix.
Generic functionqr frombase,whose default methodqr.default “defines”the S3 classqr of dense QR factorizations.
qr-methods for methods defined inMatrix.
Generic functionsexpand1 andexpand2.
The many auxiliary functions for QR factorizations:qr.Q,qr.R,qr.X,qr.coef,qr.fitted,qr.resid,qr.qty,qr.qy, andqr.solve.
Examples
showClass("sparseQR")set.seed(2)m <- 300Ln <- 60LA <- rsparsematrix(m, n, 0.05)## With dimnames, to see that they are propagated :dimnames(A) <- dn <- list(paste0("r", seq_len(m)), paste0("c", seq_len(n)))(qr.A <- qr(A))str(e.qr.A <- expand2(qr.A, complete = FALSE), max.level = 2L)str(E.qr.A <- expand2(qr.A, complete = TRUE), max.level = 2L)t(sapply(e.qr.A, dim))t(sapply(E.qr.A, dim))## Horribly inefficient, but instructive :slowQ <- function(V, beta) { d <- dim(V) Q <- diag(d[1L]) if(d[2L] > 0L) { for(j in d[2L]:1L) { cat(j, "\n", sep = "") Q <- Q - (beta[j] * tcrossprod(V[, j])) %*% Q } } Q}ae1 <- function(a, b, ...) all.equal(as(a, "matrix"), as(b, "matrix"), ...)ae2 <- function(a, b, ...) ae1(unname(a), unname(b), ...)## A ~ P1' Q R P2' ~ P1' Q1 R1 P2' in floating pointstopifnot(exprs = { identical(names(e.qr.A), c("P1.", "Q1", "R1", "P2.")) identical(names(E.qr.A), c("P1.", "Q" , "R" , "P2.")) identical(e.qr.A[["P1."]], new("pMatrix", Dim = c(m, m), Dimnames = c(dn[1L], list(NULL)), margin = 1L, perm = invertPerm(qr.A@p, 0L, 1L))) identical(e.qr.A[["P2."]], new("pMatrix", Dim = c(n, n), Dimnames = c(list(NULL), dn[2L]), margin = 2L, perm = invertPerm(qr.A@q, 0L, 1L))) identical(e.qr.A[["R1"]], triu(E.qr.A[["R"]][seq_len(n), ])) identical(e.qr.A[["Q1"]], E.qr.A[["Q"]][, seq_len(n)] ) identical(E.qr.A[["R"]], qr.A@R) ## ae1(E.qr.A[["Q"]], slowQ(qr.A@V, qr.A@beta)) ae1(crossprod(E.qr.A[["Q"]]), diag(m)) ae1(A, with(e.qr.A, P1. %*% Q1 %*% R1 %*% P2.)) ae1(A, with(E.qr.A, P1. %*% Q %*% R %*% P2.)) ae2(A.perm <- A[qr.A@p + 1L, qr.A@q + 1L], with(e.qr.A, Q1 %*% R1)) ae2(A.perm , with(E.qr.A, Q %*% R ))})## More identitiesb <- rnorm(m)stopifnot(exprs = { ae1(qrX <- qr.X (qr.A ), A) ae2(qrQ <- qr.Q (qr.A ), with(e.qr.A, P1. %*% Q1)) ae2( qr.R (qr.A ), with(e.qr.A, R1)) ae2(qrc <- qr.coef (qr.A, b), with(e.qr.A, solve(R1 %*% P2., t(qrQ)) %*% b)) ae2(qrf <- qr.fitted(qr.A, b), with(e.qr.A, tcrossprod(qrQ) %*% b)) ae2(qrr <- qr.resid (qr.A, b), b - qrf) ae2(qrq <- qr.qy (qr.A, b), with(E.qr.A, P1. %*% Q %*% b)) ae2(qr.qty(qr.A, qrq), b)})## Sparse and dense computations should agree hereqr.Am <- qr(as(A, "matrix")) # <=> qr.default(A)stopifnot(exprs = { ae2(qrX, qr.X (qr.Am )) ae2(qrc, qr.coef (qr.Am, b)) ae2(qrf, qr.fitted(qr.Am, b)) ae2(qrr, qr.resid (qr.Am, b))})Sparse Vector Construction from Nonzero Entries
Description
User friendly construction of sparse vectors,i.e., objects inheriting fromclasssparseVector, from indices and values of itsnon-zero entries.
Usage
sparseVector(x, i, length)Arguments
x | vector of the non zero entries; may be missing in which case a |
i | integer vector (of the same length as |
length | length of the sparse vector. |
Details
zero entries inx are dropped automatically, analogously asdrop0() acts on sparse matrices.
Value
a sparse vector, i.e., inheriting fromclasssparseVector.
Author(s)
Martin Maechler
See Also
sparseMatrix() constructor for sparse matrices;the classsparseVector.
Examples
str(sv <- sparseVector(x = 1:10, i = sample(999, 10), length=1000))sx <- c(0,0,3, 3.2, 0,0,0,-3:1,0,0,2,0,0,5,0,0)ss <- as(sx, "sparseVector")stopifnot(identical(ss, sparseVector(x = c(2, -1, -2, 3, 1, -3, 5, 3.2), i = c(15L, 10:9, 3L,12L,8L,18L, 4L), length = 20L)))(ns <- sparseVector(i= c(7, 3, 2), length = 10))stopifnot(identical(ns, new("nsparseVector", length = 10, i = c(2, 3, 7))))Sparse Vector Classes
Description
Sparse Vector Classes: The virtual mother class"sparseVector" has the five actual daughter classes"dsparseVector","isparseVector","lsparseVector","nsparseVector", and"zsparseVector", where we've mainly implemented methods forthed*,l* andn* ones.
Slots
length:class
"numeric"- thelengthof the sparse vector. Note that"numeric"can beconsiderably larger than the maximal"integer",.Machine$integer.max, on purpose.i:class
"numeric"- the (1-based) indices ofthe non-zero entries. Mustnot beNAand strictlysorted increasingly.Note that
"integer"is “part of”"numeric",and can (and often will) be used for non-huge sparseVectors.x:(for all but
"nsparseVector"):the non-zero entries. This is of class"numeric"for class"dsparseVector","logical"for class"lsparseVector", etc.
Methods
- length
signature(x = "sparseVector"): simply extractsthelengthslot.- show
signature(object = "sparseVector"): Theshowmethod for sparse vectors prints“structural” zeroes as"."using thenon-exportedprSpVectorfunction which allows furthercustomization such as replacing"."by" "(blank).Note that
options(max.print)will influence how manyentries of large sparse vectors are printed at all.- as.vector
signature(x = "sparseVector", mode = "character")coerces sparse vectors to “regular”, i.e., atomic vectors.This is the same asas(x, "vector").- as
..: see
coercebelow- coerce
signature(from = "sparseVector", to = "sparseMatrix"), and- coerce
signature(from = "sparseMatrix", to = "sparseVector"),etc: coercions to and from sparse matrices (sparseMatrix) areprovided and work analogously as in standardR, i.e., a vector iscoerced to a 1-column matrix.- dim<-
signature(x = "sparseVector", value = "integer")coerces a sparse vector to a sparse Matrix, i.e., an objectinheriting fromsparseMatrix, of theappropriate dimension.- head
signature(x = "sparseVector"): as withR's(packageutil)head,head(x,n)(forn >= 1) is equivalent tox[1:n], but here can be muchmore efficient, see the example.- tail
signature(x = "sparseVector"): analogous tohead, see above.- toeplitz
signature(x = "sparseVector"): astoeplitz(x), produce then \times nToeplitz matrix fromx, wheren = length(x).- rep
signature(x = "sparseVector")repeatx,with the same argument list(x, times, length.out, each,...)as the default method for rep().- which
signature(x = "nsparseVector")and- which
signature(x = "lsparseVector")return theindices of the non-zero entries (which is trivial for sparse vectors).- Ops
signature(e1 = "sparseVector", e2 = "*"): definearithmetic, compare and logic operations, (seeOps).- Summary
signature(x = "sparseVector"): defineall theSummarymethods.- is.na, is.finite, is.infinite
(x = "sparseVector"), and- is.na, is.finite, is.infinite
(x = "nsparseVector"):returnlogicalor"nsparseVector"of the samelength asx, indicating if/wherexisNA(orNaN), finite or infinite, entirelyanalogously to the corresponding baseR functions.- zapsmall
signature(x = "sparseVectors"): typically used fornumeric sparse vector:round()entriessuch that (relatively) very small entries become zero exactly.
c.sparseVector() is an S3 method for all"sparseVector"s, but automatic dispatch only happens for thefirst argument, so it is useful also as regularR function, see theexamples.
See Also
sparseVector() for friendly construction of sparsevectors (apart fromas(*, "sparseVector")).
Examples
getClass("sparseVector")getClass("dsparseVector")sx <- c(0,0,3, 3.2, 0,0,0,-3:1,0,0,2,0,0,5,0,0)(ss <- as(sx, "sparseVector"))ix <- as.integer(round(sx))(is <- as(ix, "sparseVector")) ## an "isparseVector" (!)(ns <- sparseVector(i= c(7, 3, 2), length = 10)) # "nsparseVector"## rep() works too:(ri <- rep(is, length.out= 25))## Using `dim<-` as in base R :r <- ssdim(r) <- c(4,5) # becomes a sparse Matrix:r## or coercion (as as.matrix() in base R):as(ss, "Matrix")stopifnot(all(ss == print(as(ss, "CsparseMatrix"))))## currently has "non-structural" FALSE -- printing as ":"(lis <- is & FALSE)(nn <- is[is == 0]) # all "structural" FALSE## NA-casesN <- sx; sN[4] <- NA(svN <- as(sN, "sparseVector"))v <- as(c(0,0,3, 3.2, rep(0,9),-3,0,-1, rep(0,20),5,0), "sparseVector")v <- rep(rep(v, 50), 5000)set.seed(1); v[sample(v@i, 1e6)] <- 0str(v)system.time(for(i in 1:4) hv <- head(v, 1e6))## user system elapsed## 0.033 0.000 0.032system.time(for(i in 1:4) h2 <- v[1:1e6])## user system elapsed## 1.317 0.000 1.319stopifnot(identical(hv, h2), identical(is | FALSE, is != 0), validObject(svN), validObject(lis), as.logical(is.na(svN[4])), identical(is^2 > 0, is & TRUE), all(!lis), !any(lis), length(nn@i) == 0, !any(nn), all(!nn), sum(lis) == 0, !prod(lis), range(lis) == c(0,0))## create and use the t(.) method:t(x20 <- sparseVector(c(9,3:1), i=c(1:2,4,7), length=20))(T20 <- toeplitz(x20))stopifnot(is(T20, "symmetricMatrix"), is(T20, "sparseMatrix"), identical(unname(as.matrix(T20)), toeplitz(as.vector(x20))))## c() method for "sparseVector" - also available as regular function(c1 <- c(x20, 0,0,0, -10*x20))(c2 <- c(ns, is, FALSE))(c3 <- c(ns, !ns, TRUE, NA, FALSE))(c4 <- c(ns, rev(ns)))## here, c() would produce a list {not dispatching to c.sparseVector()}(c5 <- c.sparseVector(0,0, x20))## checking (consistency).v <- as.vector.s <- function(v) as(v, "sparseVector")stopifnot(exprs = { all.equal(c1, .s(c(.v(x20), 0,0,0, -10*.v(x20))), tol = 0) all.equal(c2, .s(c(.v(ns), .v(is), FALSE)), tol = 0) all.equal(c3, .s(c(.v(ns), !.v(ns), TRUE, NA, FALSE)), tol = 0) all.equal(c4, .s(c(.v(ns), rev(.v(ns)))), tol = 0, check.class = FALSE) all.equal(c5, .s(c(0,0, .v(x20))), tol = 0)})Methods for "[<-" - Assigning to Subsets for 'Matrix'
Description
Methods for"[<-", i.e., extraction or subsetting mostly ofmatrices, in packageMatrix.
Note: Contrary to standardmatrix assignment inbaseR, inx[..] <- val it is typically anerror (seestop) when thetype orclass ofval would require the class ofx to be changed, e.g.,whenx is logical, say"lsparseMatrix", andvalis numeric.In other cases, e.g., whenx is a"nsparseMatrix" andval is notTRUE orFALSE, a warning is signalled,andval is “interpreted” aslogical, and(logical)NA is interpreted asTRUE.
Methods
There aremany many more than these:
- x = "Matrix", i = "missing", j = "missing", value= "ANY"
is currently a simple fallback method implementation which ensures“readable” error messages.
- x = "Matrix", i = "ANY", j = "ANY", value= "ANY"
currentlygives an error
- x = "denseMatrix", i = "index", j = "missing", value= "numeric"
...
- x = "denseMatrix", i = "index", j = "index", value= "numeric"
...
- x = "denseMatrix", i = "missing", j = "index", value= "numeric"
...
See Also
[-methods for subsetting"Matrix" objects; theindex class;Extract about the standard subset assignment (and extraction).
Examples
set.seed(101)(a <- m <- Matrix(round(rnorm(7*4),2), nrow = 7))a[] <- 2.2 # <<- replaces **every** entrya## as do these:a[,] <- 3 ; a[TRUE,] <- 4m[2, 3] <- 3.14 # simple numberm[3, 3:4]<- 3:4 # simple numeric of length 2## sub matrix assignment:m[-(4:7), 3:4] <- cbind(1,2:4) #-> upper right corner of 'm'm[3:5, 2:3] <- 0m[6:7, 1:2] <- Diagonal(2)m## rows or columns only:m[1,] <- 10m[,2] <- 1:7m[-(1:6), ] <- 3:0 # not the first 6 rows, i.e. only the 7thas(m, "sparseMatrix")Methods for "[": Extraction or Subsetting in Package 'Matrix'
Description
Methods for"[", i.e., extraction or subsetting mostly ofmatrices, in packageMatrix.
Methods
There are more than these:
- x = "Matrix", i = "missing", j = "missing", drop= "ANY"
...
- x = "Matrix", i = "numeric", j = "missing", drop= "missing"
...
- x = "Matrix", i = "missing", j = "numeric", drop= "missing"
...
- x = "dsparseMatrix", i = "missing", j = "numeric", drop= "logical"
...
- x = "dsparseMatrix", i = "numeric", j = "missing", drop= "logical"
...
- x = "dsparseMatrix", i = "numeric", j = "numeric", drop= "logical"
...
See Also
[<–methods for subassignment to"Matrix"objects.Extract about the standard extraction.
Examples
str(m <- Matrix(round(rnorm(7*4),2), nrow = 7))stopifnot(identical(m, m[]))m[2, 3] # simple numberm[2, 3:4] # simple numeric of length 2m[2, 3:4, drop=FALSE] # sub matrix of class 'dgeMatrix'## rows or columns only:m[1,] # first row, as simple numeric vectorm[,1:2] # sub matrix of first two columnsshowMethods("[", inherited = FALSE)Virtual Class of Symmetric Matrices in Package Matrix
Description
The virtual class of symmetric matrices,"symmetricMatrix",from the packageMatrix contains numeric and logical, dense andsparse matrices, e.g., see the examples with the “actual”subclasses.
The main use is in methods (and C functions) that can deal withall symmetric matrices, and inas(*, "symmetricMatrix").
Slots
Dim, Dimnamesinherited from virtual class
Matrix. See comments below aboutsymmetry ofDimnames.factorsa list of
MatrixFactorizationobjects cachingfactorizations of the matrix. Typically, it is initializedas an empty list and updated “automagically” whenevera factorization is computed.uploa character string, either
"U"or"L"indicating that only entries in the upper or lowertriangle are referenced.
Extends
Class"Matrix", directly.
Methods
- dimnames
signature(object = "symmetricMatrix"):returnssymmetricdimnames, even when theDimnamesslot only has row or column names. This allows tosave storage for large (typically sparse) symmetric matrices.- isSymmetric
signature(object = "symmetricMatrix"):returnsTRUEtrivially.
There's a C functionsymmetricMatrix_validate()called by the internal validity checking functions, and also fromgetValidity(getClass("symmetricMatrix")).
Validity anddimnames
The validity checks do not require a symmetricDimnames slot,so it can belist(NULL, <character>), e.g., for efficiency.However,dimnames() and other functions and methodsshould behave as if the dimnames were symmetric, i.e., with both listcomponents identical.
See Also
isSymmetric which has efficient methods(isSymmetric-methods) for theMatrix classes.ClassestriangularMatrix, and, e.g.,dsyMatrix for numericdense matrices, orlsCMatrix for a logicalsparse matrix class.
Examples
## An example about the symmetric Dimnames:sy <- sparseMatrix(i= c(2,4,3:5), j= c(4,7:5,5), x = 1:5, dims = c(7,7), symmetric=TRUE, dimnames = list(NULL, letters[1:7]))sy # shows symmetrical dimnamessy@Dimnames # internally only one part is storeddimnames(sy) # both parts - as sy *is* symmetricalshowClass("symmetricMatrix")## The names of direct subclasses:scl <- getClass("symmetricMatrix")@subclassesdirectly <- sapply(lapply(scl, slot, "by"), length) == 0names(scl)[directly]## Methods -- applicaple to all subclasses above:showMethods(classes = "symmetricMatrix")Symmetric Part and Skew(symmetric) Part of a Matrix
Description
symmpart(x) computes the symmetric part(x + t(x))/2 andskewpart(x) theskew symmetric part(x - t(x))/2 of a square matrixx,more efficiently for specific Matrix classes.
Note thatx == symmpart(x) + skewpart(x) for all squarematrices – apart from extraneousNA values in the RHS.
Usage
symmpart(x)skewpart(x)Arguments
x | asquare matrix; either “traditional” of class |
Details
These are generic functions with several methods for different matrixclasses, use e.g.,showMethods(symmpart) to see them.
If the row and column names differ, the result will use the columnnames unless they are (partly)NULL where the row names arenon-NULL (see also the examples).
Value
symmpart(x) returns a symmetric matrix,inheriting fromsymmetricMatrixordiagonalMatrix ifxinherits fromMatrix.
skewpart(x) returns a skew-symmetric matrix,inheriting fromgeneralMatrix,symmetricMatrix ordiagonalMatrix ifxinherits fromMatrix.
See Also
Examples
m <- Matrix(1:4, 2,2)symmpart(m)skewpart(m)stopifnot(all(m == symmpart(m) + skewpart(m)))dn <- dimnames(m) <- list(row = c("r1", "r2"), col = c("var.1", "var.2"))stopifnot(all(m == symmpart(m) + skewpart(m)))colnames(m) <- NULLstopifnot(all(m == symmpart(m) + skewpart(m)))dimnames(m) <- unname(dn)stopifnot(all(m == symmpart(m) + skewpart(m)))## investigate the current methods:showMethods(skewpart, include = TRUE)Virtual Class of Triangular Matrices in Package Matrix
Description
The virtual class of triangular matrices,"triangularMatrix",the packageMatrix containssquare (nrow ==ncol) numeric and logical, dense and sparse matrices, e.g.,see the examples.A main use of the virtual class is in methods (and C functions) thatcan deal with all triangular matrices.
Slots
uplo:String (of class
"character"). Must beeither "U", for upper triangular, and "L", for lower triangular.diag:String (of class
"character"). Must beeither"U", for unit triangular (diagonal is all ones), or"N"for non-unit. The diagonal elements are notaccessed internally whendiagis"U". FordenseMatrixclasses, they need to beallocated though, such that the length of thexslot does notdepend ondiag.Dim,Dimnames:The dimension (a length-2
"integer") and corresponding names (orNULL),inherited from theMatrix, see there.
Extends
Class"Matrix", directly.
Methods
There's a C functiontriangularMatrix_validity()called by the internal validity checking functions.
Currently,Schur,isSymmetric andas() (i.e.coerce) have methods withtriangularMatrix in their signature.
See Also
isTriangular() for testing any matrix for triangularity;classessymmetricMatrix, and, e.g.,dtrMatrix for numericdense matrices, orltCMatrix for a logicalsparse matrixsubclass of"triangularMatrix".
Examples
showClass("triangularMatrix")## The names of direct subclasses:scl <- getClass("triangularMatrix")@subclassesdirectly <- sapply(lapply(scl, slot, "by"), length) == 0names(scl)[directly](m <- matrix(c(5,1,0,3), 2))as(m, "triangularMatrix")Virtual Class"unpackedMatrix" of Unpacked Dense Matrices
Description
Class"unpackedMatrix" is thevirtual class of densematrices in "unpacked" format, storing allm*n elements ofanm-by-n matrix. It is used to define common methodsfor efficient subsetting, transposing, etc. of itspropersubclasses: currently"[dln]geMatrix" (unpacked general),"[dln]syMatrix" (unpacked symmetric),"[dln]trMatrix"(unpacked triangular), and subclasses of these, such as"dpoMatrix".
Slots
Dim,Dimnames:as all
Matrixobjects.
Extends
Class"denseMatrix", directly.Class"Matrix", by class"denseMatrix",distance 2.
Methods
- pack
signature(x = "unpackedMatrix"): ...- unpack
signature(x = "unpackedMatrix"): ...- isSymmetric
signature(object = "unpackedMatrix"): ...- isTriangular
signature(object = "unpackedMatrix"): ...- isDiagonal
signature(object = "unpackedMatrix"): ...- t
signature(x = "unpackedMatrix"): ...- diag
signature(x = "unpackedMatrix"): ...- diag<-
signature(x = "unpackedMatrix"): ...
Author(s)
Mikael Jagan
See Also
pack andunpack; its virtual "complement""packedMatrix"; its proper subclasses"dsyMatrix","ltrMatrix", etc.
Examples
showClass("unpackedMatrix")showMethods(classes = "unpackedMatrix")Updating and Downdating Sparse Cholesky Factorizations
Description
Computes a rank-k update or downdate of a sparse Choleskyfactorization
P_{1} A P_{1}' = L_{1} D L_{1}' = L L'
which for somek-column matrixC is the factorization
P_{1} (A + s C C') P_{1}' = \tilde{L}_{1} \tilde{D} \tilde{L}_{1}' = \tilde{L} \tilde{L}'
Here,s = 1 for an update ands = -1 for a downdate.
Usage
updown(update, C, L)Arguments
update | a logical ( |
C | afinite matrix or |
L | an object of class |
Value
A sparse Cholesky factorization with dimensions matchingL,typically of classdCHMsimpl.
Author(s)
Initial implementation by Nicholas Nagle, University of Tennessee.
References
Davis, T. A., Hager, W. W. (2001).Multiple-rank modifications of a sparse Cholesky factorization.SIAM Journal on Matrix Analysis and Applications,22(4), 997-1013.doi:10.1137/S0895479899357346
See Also
ClassesdCHMsimpl anddCHMsuperand their methods, notably for generic functionupdate,which isnot equivalent toupdown(update = TRUE).
Generic functionCholesky.
Examples
m <- sparseMatrix(i = c(3, 1, 3:2, 2:1), p = c(0:2, 4, 4, 6), x = 1:6, dimnames = list(LETTERS[1:3], letters[1:5]))uc0 <- Cholesky(A <- crossprod(m) + Diagonal(5))uc1 <- updown("+", Diagonal(5, 1), uc0)uc2 <- updown("-", Diagonal(5, 1), uc1)stopifnot(all.equal(uc0, uc2))Contiguity Matrix of World One-Degree Grid Cells
Description
This matrix gives the contiguities of 15260 one-degreegrid cells of world land areas, using a criterion basedon the great-circle distance between centers.
Usage
data(wrld_1deg)Format
A15260 \times 15260 sparse, symmetricmatrix of classdsCMatrix, with 55973nonzero entries.
Source
Shoreline data were read intoR from the GSHHS databaseusing functionRgshhs from packagemaptools.Antarctica was excluded. An approximately one-degree gridwas generated using functionSobj_SpatialGrid, alsofrommaptools. Grid cells with centers on landwere identified using theover method for classesSpatialPolygons andSpatialGrid, defined inpackagesp. Neighbours of these were identifiedby passing the resultingSpatialPixels object tofunctiondnearneigh from packagespdep,using as a cut-off a great-circle distance ofsqrt(2)kilometers between centers.
Neighbour lists were augmented with row-standardized(and then symmetrized) spatial weights, using functionsnb2listw andsimilar.listw from packagesspdep andspatialreg.The resultinglistw object was coerced to classdsTMatrixusingas_dsTMatrix_listw fromspatialreg,and subsequently to classdsCMatrix.
References
Ord, J. K. (1975).Estimation methods for models of spatial interaction.Journal of the American Statistical Association,70(349), 120-126.doi:10.2307/2285387
Examples
data(wrld_1deg, package = "Matrix")(n <- ncol(wrld_1deg))I <- .symDiagonal(n)doExtras <- interactive() || nzchar(Sys.getenv("R_MATRIX_CHECK_EXTRA"))set.seed(1)r <- if(doExtras) 20L else 3Lrho <- 1 / runif(r, 0, 0.5)system.time(MJ0 <- sapply(rho, function(mult) determinant(wrld_1deg + mult * I, logarithm = TRUE)$modulus))## Can be done faster by updating the Cholesky factor:C1 <- Cholesky(wrld_1deg, Imult = 2)system.time(MJ1 <- sapply(rho, function(mult) determinant(update(C1, wrld_1deg, mult), sqrt = FALSE)$modulus))stopifnot(all.equal(MJ0, MJ1))C2 <- Cholesky(wrld_1deg, super = TRUE, Imult = 2)system.time(MJ2 <- sapply(rho, function(mult) determinant(update(C2, wrld_1deg, mult), sqrt = FALSE)$modulus))stopifnot(all.equal(MJ0, MJ2))