| NEWS | R Documentation |
News forR PackageMatrix
Changes in version 1.7-4 (2025-08-27, svn r5172)
Installation
Warnings surfaced by-Wtautological-overlap-compareare squashed. These revealed two typos in ‘src/matmult.c’causing optimizations for
crossprod(.sRMatrix, y)andtcrossprod(x,.sRMatrix)to be skipped. Thanks toBrian Ripley and Michael Chirico for the reports.
Bug Fixes
Methods for
band,triu, andtrilwithsignaturex="matrix"returned a formally invalid.geMatrix(withxslot of class"matrix") insome no-op cases, where no bands are set to zero.
Changes in version 1.7-3 (2025-03-05, svn r5126)
Bug Fixes
<matrix>o<sparseVector>binary"Ops"work again, returning a matrix (of"Matrix").- new("lgeMatrix")and more- <Matrix>now work.Use
intinstead ofRbooleanin 2x2 cases in ‘utils-R.c’.
Changes in version 1.7-2 (2025-01-20, svn r5115)
Installation
Matrix can be installed with parallel
bmake.Thanks to Sebastian Meyer for the report and patch inMatrixPR#6861.
Misc
Test in ‘tests/matprod.R’ comparing
t(x) %*% xandcrossprod(x)is amended to toleratesmall numerical differences seen under ‘aarch64’ Linux.
Changes in version 1.7-1 (2024-10-17, svn r4948)
Installation
Installation under architecture-specific builds ofRworks again. It was broken inMatrix version 1.7-0,where changes to ‘src/Makevars’ resulted inCPPFLAGSnot including-I"${R_INCLUDE_DIR}${R_ARCH}".
SuiteSparse
Internal SuiteSparse and METIS library sources are patchedto avoid possible use of illegal entry points.
C-Level API
Registered routine
sexp_as_cholmod_factorno longercallscholmod_check_factorbefore returning, leaving thedecision to check to the caller. Accordingly, mostcholmod_check_*are registered; packages wanting to usethem needLinkingTo: Matrix (>= 1.7-1).
Misc
Non-API entry points
OBJECT,IS_S4_OBJECT,SET_OBJECT,ATTRIB, andSET_ATTRIBare nolonger used.
Changes in version 1.7-0 (2024-03-16, svn r4662)
Installation
Matrix
\ge1.7-0 depends onR\ge4.4.
Linking
TheMatrix ABI version is incremented from 1 to 2.
Reverse
LinkingTobuilt under earlier versions ofMatrix should be rebuilt from sources by users andmaintainers of binary repositories.
SuiteSparse
The internal SuiteSparse library sources are updated fromversion 5.10.1 to version 7.6.0. We have so far identified onebackwards incompatible change: since SuiteSparse version 7.3.0,
cholmod_sort(A)sorts butdoes not pack the matrixA. It seems that nowcholmod_sortandcholmod_copymust be used in conjuction if a sortedand packed result is desired. This change affects onlyreverseLinkingTorelying on the old behaviour. It seemsthat currently there are no such packages on CRAN or Bioconductor.CHOLMOD component Partition is compiled along with itsdependencies (METIS, CAMD, CCOLAMD).
CXSparse is compiled instead of CSparse, which did notsupport complex matrices.
The internal SuiteSparse and METIS library sources arepatched to squash a significant number of warnings surfaced by-Wall.
Significant User-Visible Changes
The diagonal elements of the
Rfactor computed byqr(<sparseMatrix>)are no longer constrained to benon-negative, due to differences in the implementation of functioncs_housebetween SuiteSparse libraries CSparse andCXSparse.
Classes
indMatrixno longer extends virtual classcompMatrixand so no longer inherits a (never used)factorsslot. Objects serialized underMatrix<1.7-0 and unserialized underMatrix\ge1.7-0 remain valid, retaining a harmlessfactorsattribute.Unexported class union
replValueSpis effectivelyremoved, now having zero members. Actual removal is delayed untilpackage binaries caching the old definition are rebuilt underMatrix version 1.7-0.The validity method for class
sparseQRno longerrequires non-negativediag(R).
Bug Fixes
The unary subscript
x[i]is correct again forxof class.s[CT]Matrixand logicaliindexing entries outside of the stored triangle.
Changes in version 1.6-5 (2024-01-06, svn r4560)
C-Level API
Registered routine
cholmod_triplet_as_sexptransposesentries “opposite” thestypewhen that is nonzero,following CHOLMOD.cholmod_defaultsis registered so that calls toAPI functionM_cholmod_defaultsactually work.
Bug Fixes
x[]works forxinheriting from virtual classsparseVector.length(x)is always an integer forxinheriting from virtual classsparseVector. Truncation didnot occur forx@lengthof type"double"equal to orgreater than.Machine[["integer.max"]] + 1.tril(<n-by-n>, -n)now works again.tri[ul](<indMatrix>, k)now works correctly fork != 0.
Misc
%||%is defined in theMatrix namespace onlyforR<4.4.0.
Changes in version 1.6-4 (2023-11-29, svn r4523)
Installation
Warnings surfaced by-Wformat are squashed.
C-Level API
API function
M_chm_triplet_to_SEXP, removed inMatrix version 1.6-2, is restored (as a macro). It was“covertly” used by packageRmosek.
Bug Fixes
better deprecation message for
..2dge().
Changes in version 1.6-3 (2023-11-13, svn r4513)
Misc
With anR built with
configureoption--disable-long-double,prod(M)now very slightlydiffers for two differently classed versions ofM.checkMatrix()from ‘test-tools-Matrix.R’ getsoptionalMSGargument for suppressingprod()differences.
Changes in version 1.6-2 (2023-11-05, svn r4503)
Compatibility
Matrix did not pass its checks underR version3.5.0, implicitly violating
Depends: R (>= 3.5). Thisrelease restores compatibility.
Linking
Support is added for an ABI version relevant to packagesthat link againstMatrix. The ABI version is 1 in thisrelease and will be incremented by 1 in each future release thatchanges the ABI. It is implicitly 0 in previous releases.Versions and their components are defined in a header for use bypackages with
LinkingTo: Matrix (>= 1.6-2)in their‘DESCRIPTION’. See ‘inst/include/Matrix/version.h’ and(below)Matrix.Version.Reverse
LinkingTobuilt under earlier versions ofMatrix should be rebuilt from sources by users andmaintainers of binary repositories.
C-Level API
API headers are organized under ‘inst/include/Matrix/’for easier namespacing. Packages should start using
LinkingTo: Matrix (>= 1.6-2)and include the API headerswith, e.g.,#include <Matrix/Matrix.h>.Packages including API headers can define macro
R_MATRIX_INLINE, typically with#define R_MATRIX_INLINE inline, in order to allow thecompiler to inline stubs for registered routines.Some API function prototypes and macros not used by anyreverse
LinkingToare removed or remapped.Several API function prototypes used
constqualifierswhere the registered routines do not.The prototype of API function
M_cholmod_band_inplacedid not match that of registered routinecholmod_band_inplace. The prototype ofcholmod_bandwas copied by mistake.
Significant User-Visible Changes
Methods for generic functions
rbind2,cbind2,%*%,%&%,crossprod, andtcrossproddetermine the class of the result using morestrict rules, designed to avoid “surprising” coercionswhere possible. Notably, operations involvingRsparseMatrixnow return anRsparseMatrixin morecases.TsparseMatrixanddiagonalMatrixmay behandled asCsparseMatrixor asRsparseMatrix,depending on context.
Classes
New nonvirtual class
ndiMatrixrepresenting diagonalnonzero pattern matrices. It extends virtual classesdiagonalMatrixandnMatrix.ndiMatrixaretypically obtained as the result ofis.na,is.nan,oris.infiniteapplied to adiagonalMatrixor as theresult of coercing adiagonalMatrixtonMatrix.(The result of that coercion used to be anntCMatrix. Itis still possible to obtain anntCMatrixby coercion tonsparseMatrix.)The validity method for class
sparseVectorrequireslengthnot exceeding2^53, which on most platformsis the minimum positive integerksuch thatk + 1isnot exactly representable in double precision.A
dsparseVectorwithxslot of type"integer"is formally invalid, as always intended.Certain never or seldom used class unions are removed.
New Features
mean(<sparseVector>, trim=)now works efficiently fornonzero values oftrim.rep(<sparseVector>, each=)now works efficiently,avoidingrep(., times = rep(each, times = length(.)))..m2denseand.m2sparsegain an argumenttransindicating if vectors that are not matrices should becoerced to 1-row matrices rather than 1-column matrices..m2denseand.m2sparsecan be called with oneargument. Theirclassarguments admit new default values".ge"and".gC"..diag2denseand.diag2sparsegain an argumentkindindicating the “kind” of the result.New exports
.M2Vand.m2V, for coercingMatrixandmatrix(and in factvector) tosparseVector.New exports
isUniqueTandasUniqueT, withoptional argumentbyrowallowing for row-major ordering ofentries.asUniqueTsupercedesuniqTsparse, which isno longer documented.New export
aggregateT, for aggregatingTsparseMatrixwithout sorting.Methods for
all.equalnow report the packages whereS4 classes are defined.sum(x)andprod(x)no longer require acoercion fromsymmetricMatrixtogeneralMatrix.Results where coercions are now avoided may differ numerically dueto reordering of adds and multiplies, most commonly on systemswheresizeof(long double) == sizeof(double).
Bug Fixes
Methods for
cbind2andrbind2did not in allcases handle vectors as 1-column and 1-row matrices, respectively.Methods for
cbind2andrbind2did not handle0-length vectors (includingNULL) correctly where theresult would have 0 rows and columns, respectively.Methods for
cbind2andrbind2did not handleNAin thexslot ofndenseMatrixcorrectly(i.e., asTRUE).cbind2(<ndenseMatrix>, <ldenseMatrix>)gavengeMatrixinstead oflgeMatrix.cbind2(<lsparseMatrix>, <lsparseMatrix>)gavedgCMatrixinstead oflgCMatrix. Methods forrbind2had similar problems.rcond(<0-by-0>)now returnsInf; seePR#18543.round(<dp[op]Matrix>)andsignif(<dp[op]Matrix>)now returnds[yp]Matrixrather thandp[op]Matrixand now discardfactors.Methods for
lengthnow returnintegerratherthandoubleif the result does not exceedINT_MAX.Methods for subscripting
sparseVectordid not behavecompatibly withbase when supplied with fractional,NA, or out-of-bounds subscripts.symmpart(x),skewpart(x),band(x, k1, k2),triu(x, k), andtril(x, k)now always return a.diMatrixforxinheriting fromdiagonalMatrix.colSums(<(n|l|ind)Matrix>)androwSums(<(n|l|ind)Matrix>)now always give a result of type"integer". Methods differed previously, some giving"double"(asbase does, suboptimally, traditionalmatrices of type"logical").Some methods for generic function
ludid not transmitDimnamesto the result.Some methods for group generic function
Summaryignored arguments matching.... Other methods did notignore the “garbage” elements of thexslot ofdense, triangular matrices.kronecker(<n.TMatrix>, <diagonalMatrix>)threw anerror for attempting to access the nonexistentxslot ofits first argument.Matrix products now behave exactly asbase whentesting for conformable arguments.
Numeric products (
%*%) did not always return adMatrix.Methods for
all.equalnow “see” attributes ofS4 objects that are not slots. This can be disabled by settingargumentcheck.attributestoNA, which is otherwiseequivalent toTRUE.prod(x)is computed more diligently forxinheriting fromsparseMatrix,sparseVector, or.t[rp]Matrix, i.e., thosexthat can be understoodto have “structural” zeros. Now, multiplication by zerooccurs at the position of the first structural zero in the matrixor vector (when traversed by row in the case ofRsparseMatrix). An exception isTsparseMatrix, forwhich multiplication by zero occurs before multiplication by anystored entry, regardless of the position of the first structuralzero in the corresponding sorted matrix (to avoid the cost ofsorting).tri[ul](<.t[rp]Matrix>, k)was often wrong fornonzerok, setting too many bands to zero.C-level
tCsparse_diag(formerlydiag_tC) nowhandles structural zeros andNaNon the main diagonalcorrectly. Option"diagBack"now works correctly.expm(x)failed forxof classdtpMatrixordspMatrix, sinceMatrix version 1.6-1..m2dense(x, ".ge")allocated unnecessarily forxwithout attributes.
Misc
C code now refers to the symbol
factorsasMatrix_factorsSym, rather thanMatrix_factorSym.The content of ‘src/Mutils.[ch]’ has been migrated tomore transparently named files: ‘src/attrib.[ch]’,‘src/objects.[ch]’, etc. Similarly, much of‘src/factorizations.[ch]’ have been migrated to‘src/solve.[ch]’ and ‘src/determinant.[ch]’.
All matrix product code has been migrated to‘products.[Rch]’.
Files in ‘po/’ and ‘inst/po/’ have been updateddue to more frequent use of
gettextfin ‘R/*.R’.C code is prepared to handle complex matrices andtheir factorizations. Notably, new machinery in‘src/cs-etc.[ch]’ will enable linking the CXSparse libraryinstead of the CSparse library, the latter supporting numerictypes but not complex ones.
Changes in version 1.6-1.1 (2023-09-08, hotfix)
Misc
Export the generics
crossprod()andtcrossprod()explicitly, needed for R-devel when theybecome primitive internal generics.
Changes in version 1.6-1 (2023-08-11, svn r4228)
C-Level API
Registered routine
chm_sparse_to_SEXPsorts and packsits first argumentbefore assigning any struct members tovariables, preventing use-after-free.
Memory
Four Valgrind-detected memory bugs are fixed.
Classes
Validity methods for classes
CholeskyandpCholeskytest for a validpermslot.
New Features
Several new coercion utilities, exported and documented in
help("fastMisc"). Some of these supercede ones madeavailable (experimentally) inMatrix 1.5-4; for example,.M2mmakes both.dense2mand.sparse2mredundant. The superceded ones are not yet formally deprecated,but are no longer documented.drop0is now implemented independently ofCHOLMOD, becoming more efficient notably for logicalarguments, no longer requiring a coercion to double.drop0gains an argumentgive.Csparsetocomplementis.Csparse.FALSEindicates thatRsparseMatrix,TsparseMatrix, andindMatrixarguments should be handled directly, without a coercion toCsparseMatrix. The default value isTRUE, forbackwards compatibility.
Bug Fixes
<diagonalMatrix> %*% <RsparseMatrix>works again.diag(<non-square RsparseMatrix>) <- valueworksagain, no longer giving apslot of lengthDim[2]rather thanDim[1].as(<diagonalMatrix>, "symmetricMatrix")now checksfor symmetricDimnames, for consistency.as(<indMatrix>, "[nld](sparse)?Matrix") now returns a
.gRMatrixor a.gCMatrixdepending on themarginslot.as(<[CR]sparseMatrix>, "generalMatrix")now checks ifthe number of nonzero entries in the result would exceedINT_MAXand throws an error in that case.
Misc
Run speed-measuring tests only
if(doExtras): thesewere too slow when run under Valgrind.Most coercion code has been migrated to ‘coerce.[Rch]’from elsewhere.
The number of methods for generic functions
coerceandas.*has been reduced substantially, from 306 to 194(not counting deprecated ones), partly as a result of efforts todo more fine-grained dispatch in C code.Files in ‘po/’ and ‘inst/po/’ have been updated(again), as many more C level messages now use formatstrings as a result of
vsnprintfusage in‘src/validity.c’.
Changes in version 1.6-0 (2023-06-30, svn r4125)
Dependencies
The following “weak” dependencies, needed only for asmall number of Rd cross references, are removed:MatrixModels,expm,igraph,maptools,sp,spdep. Links to CRAN or Bioconductor in Rd filesare preserved.
sfsmisc is moved from
EnhancestoSuggests, asMatrix does not formally enhance it withmethods or links to documentation.grDevices anddatasets are added to
ImportsandSuggests, respectively, asMatrixdoes import fromgrDevices and (in vignettes) does load datafromdatasets.Example, test, and vignette code no longer fails whenR_DEFAULT_PACKAGES is set to
NULL.Example code uses
requireNamespaceinstead ofrequireto preserve the user's search path.
Significant User-Visible Changes
Methods for generic function
cholthat previouslyreturned an object of classp?Choleskynow return anequivalent object of classdtrMatrixordtpMatrix.Existing code that relied (correctly) oncholto return theupper triangular Cholesky factor as aMatrixcan beexpected to work as before.
Classes
Class
indMatrixgains amarginslot with value1Lor2L(1Lbeing the prototype andpreviously implicit value), indicating that the object representsa row or column index matrix, with ones at[i, perm[i]]or[perm[j], j], respectively.
Methods withindMatrixor its subclasspMatrixinthe signature have been adjusted to account for the new slot.Notably, multiplication on the right by anindMatrixwithmargin = 2is now implemented as a column subscript, andthe transpose of anindMatrixis now the same object butwith “opposite”margin.Virtual class
MatrixFactorizationgains aDimnamesslot. Now all factorizations preserve theDimnamesof the original, factorizedMatrix, whereaspreviously classesSchur,sparseLU,sparseQR,dCHMsimpl, anddCHMsuperdidnot. Users canget the value of the newDimnamesslot withdimnames(.)and set it withdimnames(.) <- value.Classes
p?BunchKaufmanandp?Choleskynolonger extenddtrMatrixordtpMatrixand in turn nolonger extendMatrix. They retain slotsDim,Dimnames,uplo, andx, but notdiag.This change implies that virtual classesMatrixandMatrixFactorizationno longer intersect.Classes
p?Choleskygain apermslot withprototypeinteger(0L)to support representation of pivotedfactorizations, as typically computed by LAPACK routinedpstrf.permof length 0 is valid and equivalent tothe identity permutation.New nonvirtual class
pcorMatrixextendingdppMatrix. It is the counterpart ofcorMatrixusingpacked storage, supporting more efficient storage of densecorrelation matrices. Nowpack(<corMatrix>)gives apcorMatrixpreserving thesdslot, rather than adppMatrixwithout ansdslot.New virtual classes
BunchKaufmanFactorization,SchurFactorization, andQR, extended by existingnonvirtual classesp?BunchKaufman,Schur, andsparseQR, respectively. These are parallel to the existingvirtual classesCholeskyFactorizationandLU.Packages defining new factorization classes may extend these.Virtual class
CHMfactorand its subclasses gainformal validity methods.The validity method for class
sparseQRnow tests thattheVslot is lower trapezoidal and that theRslothas non-negative diagonal elements.The validity method for class
corMatrixnow toleratesnonfinite elements in thesdslot. It no longer toleratesnonunit diagonal elements in thexslot.The prototype of the
Dimslot of virtual classMatrixFactorizationis nowinteger(2L). It waspreviouslyinteger(0L), with the result thatvalidObject(new(<nonvirtual>))was always an error.The prototype of the
Lslot of classsparseLUis now formally lower triangular, so thatvalidObject(new("sparseLU"))is not an error.The prototypes of the
QandTslots of classSchurare now 0-by-0dgeMatrix, so thatvalidObject(new("Schur"))is not an error.
Generic Functions
New generic functions
expand1andexpand2,intended to replaceexpandand coercions from (subclassesof)MatrixFactorizationto (subclasses of)Matrix.expand1is used asexpand1(<MatrixFactorization>, <character string>)andconstructs by name factors appearing in the factorization.expand2is used asexpand2(<MatrixFactorization>)and returns a named list ofall factors appearing in thefactorization, in order and with row names on the first factorand column names on the last factor. The result can be used toreconstruct the factorizedMatrixas the product of theelements of the list, namelyReduce(`%*%`, expand2(.)).expandand its methods are retained for backwardscompatibility. They may be formally deprecated in the future,hence new code should useexpand1andexpand2.Notably,expand1andexpand2have methods for allfactorizations inMatrix, whereasexpandcontinues tohave methods only fordenseLU,sparseLU, andCHMfactor. Seehelp("expand-methods")for a list ofmethods, including useful optional arguments.
New Features
Methods for subscripting
Matrixnow use the moresystematic code in ‘R/subscript.R’ and‘src/subscript.c’, becoming more efficient for alllsparseMatrix(no longer coercing todsparseMatrixand back),sparsesymmetricMatrix(no longer coercing togeneralMatrixand back wheniinx[i, i]is monotone),unpackedMatrix(no longer coercing tomatrixand back), andRsparseMatrix(no longer coercing toTsparseMatrix, then toCsparseMatrix, then back toTsparseMatrix[!]).x[i, j, drop = FALSE]preserves the class ofxinmore cases wherexis atriangularMatrix,diagonalMatrix, orpMatrix, doing more completechecks oniandj.
Notably, forxinheriting fromRsparseMatrix, theresult is now always anRsparseMatrix, rather than always aTsparseMatrix.NULLsubscripts, as inx[NULL],x[NULL, j], andx[i, NULL], are now supported forxinheriting fromMatrix. They are handled asinteger(0), consistent withbase.Generic function
Choleskygains methods fordenseMatrixreturning an object of classp?Cholesky.The method for subclassdsyMatrixadmits an argumentpermindicating if the pivoted factorization should becomputed. The correspondingcholmethod gains an argumentpivotindicating the same. By default,Choleskypivots andcholdoes not.Many subclasses of
MatrixFactorizationcan now becoerced to “nearby” subclasses ofMatrix. TheresultingMatrixreflects the internal representation ofthe factorization and not necessarily a particular matrix factor.The new coercions are:as(<denseLU>, "dgeMatrix"),as(<BunchKaufman>, "dtrMatrix"),as(<pBunchKaufman>, "dtpMatrix"),as(<Cholesky>, "dtrMatrix"),as(<pCholesky>, "dtpMatrix"),as(<CHMsimpl>, "dtCMatrix"), andas(<CHMsuper>, "dgCMatrix").Seehelp("denseLU-class")(and similar) for details.determinant(x, ...)andsolve(a, b, ...)now work forxandainheriting fromMatrixFactorization, behaving as ifxandawere replaced by the factorizedMatrix. The exception isxinheriting fromCHMfactor, where for backwardscompatibility the default behaviour is still to compute thedeterminant of the Cholesky factor. This exception should beconsideredtemporary, hence defensive code will calldeterminantwith (new) optional argumentsqrtset toTRUEorFALSEexplicitly, to not rely on the currentdefault value. Seehelp("CHMfactor-class")for details.Generic function
diaggains methods forp?CholeskyandCHMfactor. The result is a numericvector containing the diagonal entries of the diagonal matrixD, as defined inhelp("Cholesky-class")andhelp("CHMfactor-class").The
luandqrmethods for classdgCMatrixnow admit anorderargument with value in0:3, allowing the expert user to choose among all orderingmethods made available by the CSparse library.solve(<dgCMatrix>, b, sparse = TRUE)is now handledentirely in C code viacs_spsolvefrom theCSparse library.New utilities
invertPerm,signPerm,isPerm, andasPermfor computing the inverse andsign of a permutation vector, testing if an integer vector is apermutation vector, and coercing a transposition vector to apermutation vector.invertPermis a more general versionof the already exported functioninvPerm, which is retainedas a wrapper aroundinvertPermfor backwards compatibility.The
qr.Rmethod for classsparseQRgains abackPermuteargument with defaultFALSE, forcompatibility withbase. FunctionqrR, which existedprimarily to provide a back-permuting option, is retained forbackwards compatibility.
Bug Fixes
x[integer(0), ]andx[, integer(0)]now give ageneralMatrixresult whenxis a 0-by-0diagonalMatrix, for consistency with all other cases ofx[seq_len(n), ]andx[, seq_len(n)], wherexis ann-by-ntriangular, symmetric, or diagonalmatrix.For
xinheriting fromRsparseMatrix,subassignment of the formx[i, ] <- valueis now correctlydistinguished fromx[i] <- value.rownames(x[integer(0), , drop = FALSE])andcolnames(x[, integer(0), drop = FALSE])are now alwaysNULLand nevercharacter(0), consistent with theimplementation inbase.Subscript operations on
Matrixnow correctly errorwhenever the formal argument ... is matched, as inx[i, j, drop], wherex[i, j, drop = drop]is almost alwaysintended.x[i, ]now correctly drops dimensions whenxis a 1-by-nMatrixandiisTRUE.Methods for
solvenow obey the following rules muchmore strictly:solve(a=<Matrix>, b=<vector>)must return a vector.solve(a=<denseMatrix>, b=<Matrix>)must return adenseMatrix.solve(a=<sparseMatrix>, b=<Matrix>, sparse=FALSE)must return adenseMatrix.solve(a=<sparseMatrix>, b=<Matrix>, sparse=TRUE)must return asparseMatrix.
resolving some longstanding incompatibilities withbase.
Note that methods for sparseaand missing or sparsebhave defaultsparse = TRUE, while methods forsparseaand densebhave defaultsparse = FALSE.solve(<symmetricMatrix>)now always gives asymmetricMatrixresult.solve(<dpoMatrix>)andsolve(<dppMatrix>)preserve formal positive definiteness,giving adpoMatrixanddppMatrix, respectively.BunchKaufman(<matrix>)now works when argumentuplo(documented to be optional) is missing.Coercions to
corMatrixnow set the diagonal elementsof the result to 1, consistent withcov2cor.dimnames(x) <- valuenow validatesx@Dimbeforevalueto avoid undefined behaviour in C-level check.chol2inv(x)now ignores the lower triangular part ofxnot inheriting fromtriangularMatrix.chol2inv(x)now computescrossprod(solve(x))instead oftcrossprod(solve(x))for all formally lowertriangularx. Previously,crossprodwas used onlyfor densex.rcond(x, norm)throws a nicer error forxoflength 0.Error messages due to invalid
norminrcond(x, norm)now refer to the argument asnormrather thantype.rcond(x, norm)now validatesnormalso forxof classd(sy|sp|po|pp)Matrix, even if for suchxall validnormgive the same result.which(<[RT]sparseMatrix>, ...)now gives indices incolumn-major order in all cases, to be consistent withhelp("which").Factorizations inheriting from virtual class
LUarenow cached under the namedenseLUorsparseLU,depending on the nonvirtual class, rather than always under thenameLU. Note that user code shouldnot rely on thedetails of the cache and should instead rely on functions such asluto retrieve cached factorizations.Errors signaled by
as(<dsyMatrix>, "dpoMatrix")andas(<dspMatrix>, "dppMatrix")now clarify that the coercionsdo not attempt to test for positive semidefiniteness when thematrix is not positive definite.
Memory
invPerm(p)no longer segfaults forpthat arenot valid permutation vectors.invPerm(NA)was enough totrigger a segfault.C code interfacing the CSparse library tests inmore places for failed allocations inside of
cs_*.
Misc
Help pages for matrix factorization classes and methods havebeen broadly expanded and updated to use consistent notation.
The length of theMatrix namespace has been reduced by~15%. More than 100 unused symbols have been removed.
Updates to ‘po/*.{po,pot}’ and ‘inst/po/*’ fortranslators.
Changes in version 1.5-4.1 (2023-05-16, hotfix)
Installation
‘src/Lapack-etc.h’ uses
#ifdef PR18534fixed,adapting toPR#18534 without breaking installation underR<4.3.1.
Changes in version 1.5-4 (2023-04-02, svn r3837)
Compatibility
sequence.defaultis defined forR<4.0.0.
C-Level API
‘Rinternals.h’ is included in‘inst/include/Matrix.h’ instead of deprecated‘Rdefines.h’. The inclusion is done outside of
extern "C".
Deprecated and Defunct
The following low level coercion utilities, which werepreviously exported but always “hidden” and undocumented,are now deprecated:
..2dge,.C2nC,.T2Cmat,.asmatrix,.dense2sy,.diag2mat,.diag2sT,.diag2tT,.dsy2dsp,.dsy2mat,.dxC2mat,.m2dgC,.m2lgC,.m2ngC,.m2ngCn,.m2ngTn,.n2dgT,.nC2d,.nC2l.
The deprecations follow efforts to define more general and moresystematic (but still fast) coercion utilities, to allow expertusers to bypass S4 dispatch in more cases. The subset of thesecurrently exported is documented underhelp("fastMisc").Deprecation warnings will suggest an appropriate replacement,mostly from that list.
It is not always the case that the replacement can be“dropped in”, hence users should consult the relevantdocumentation when changing their code.Warnings signaled by coercion methods deprecated inMatrix 1.5-0 now correctly inherit from class
deprecatedWarning.
Memory
Calls to
sprintfare replaced by equivalent callssnprintfto avoid potential buffer overflow.
Misc
C-level utilities
Matrix_memset()andMatrix_memcpy(), both new, are now used in many placesinstead of API macrosMemzero()andMemcpy()whichnever check for overflow. C-level macroAZERO()is nolonger defined.C-level macro
Calloc_or_Alloca_TO()nowzero-initializes also in thealloca-using case.
Changes in version 1.5-3 (2022-11-10, svn r3772)
Dependencies
methods is moved from
ImportstoDependsas suggested in the WRE manual. Nowasand other basic S4machinery are available wheneverMatrix is attached. Thischange affectsR processes started with environment variableR_DEFAULT_PACKAGES set toNULL(or any list notcontainingmethods).
Compatibility
Test involving sparse
POSIXltin‘tests/Simple.R’ is adapted to possible (unconditional sinceR version 4.3.0) existence of character componentzone.
Bug Fixes
dimScale(x)with argumentd1missing is nolonger an error. (The default value haddiag(x, FALSE)instead ofdiag(x, names = FALSE).)(dim|row|col)Scale(x)is no longer an error fortraditional matricesxwithout adimnamesattribute.Our
cov2cor()methods now again preserve(symmetrized!)dimnames, fixingMatrixPR#6783 reported byBen Bolker.colSums()and friends now always give anamedresult when the marginalDimnamesare non-NULL.(Names were “forgotten” fordiagonalMatrixandindMatrixarguments.)colSums()and friends now respectna.rmwhenhandlingdiagonalMatrixwithNAdiagonal entries.expand(<denseLU>)now “copies-on-modify”, nolonger duplicating them*n-lengthxslot in them == ncase, when it can be used directly.lu(<m-by-0>),lu(<0-by-n>), andBunchKaufman(<0-by-0>)now give sensible (0-extent)results, rather than a LAPACK error, fordenseMatrix.
New Features
Diagonal()gets a new optionalnamesargument.diag(x) <- valueis now done in C also for[CRT]sparseMatrix..diagU2N()gets fast counterpart.diagN2U().colSums()and friends are now implemented moreefficiently fordenseMatrixand[CRT]sparseMatrix.Notably, methods for triangular and symmetric matrices no longergo viageneralMatrix, and methods for[CRT]sparseMatrixnow handle nonzero pattern and logicalmatrices directly (no longer coercing to double, a constraint ofthe earlier implementation using CHOLMOD).determinant(<ds[yp]Matrix>)is now computed via theBunch-Kaufman factorization. Factorizations are cached in thefactorsslot for future reuse.
Misc
C-level wrappers for LAPACK
d..trfroutines gain anargumentwarnindicating how to handleinfo > 0:warn <= 0is silent,warn = 1is a warning, andwarn > 1is an error. In the case ofdp[op]trf, forwhichinfo > 0implies an incomplete factorization,infois now returned as a length-1 integer.
Changes in version 1.5-2 (2022-10-21, svn r3702)
Classes
The validity methods for classes
l[st]CMatrixnowcorrectly test for structurally nonzero entries on the wrong sideof the main diagonal, and fail in that case. Previously, thistest was performed only ford[st]Matrix.The validity method for virtual class
sparseVectorismore diligent, catching more edge cases such asNAin thelengthorislot.New validity methods for
n[st][CRT]Matrix,Schur,denseLU,p?BunchKaufman,p?Cholesky,sparseLU, andsparseQR. Notably,the following properties of factorizations are now checked: thedimensions of each factor, the orientation of each triangular (ortrapezoidal) factor, and the validity of each permutation vector.
Bug Fixes
lu(x)@L@uplois now"L", not"U", for0-by-0 and 1-by-1dgCMatrixx.The validity method for
corMatrixnow throws a bettererror when thesdslot is of type"integer"ratherthan"double"..sparseDiagonal()now agrees withDiagonal()when called with no arguments, returning a 0-by-0 (rather than1-by-1) diagonalMatrix.sparseMatrix(i, j)with 0-lengthiandjnow returns a 0-by-0 matrix rather than throwing aperplexing error.sparseMatrix(dims = <list>)andsparseMatrix(x = <dMatrix>)now produce errors.diag(x) <- valuenow coercesdiagonalMatrixxiftypeof(value)is “higher” thantypeof(x@x)in the usual hierarchy, for consistency withmethods fordenseMatrixand withbase::`diag<-`.Methods for
kronecker()no longer ignore themake.dimnamesargument.Printing a
sparseMatrixwithNArow or columnnames is no longer an error.Products of two
pMatrixobjectsxandyare now computed correctly. Previously,y %*% xwasreturned instead ofx %*% y!Products
x %*% ywithxadiagonalMatrixorindMatrixandyatraditional matrix or vector, or withxa traditionalmatrix or vector andyadiagonalMatrixorpMatrix, now treat the unclassed argument as a.geMatrixand return a.geMatrix, for greaterconsistency with other products involving oneMatrixandone non-Matrix.Similarly,
kronecker(x, y)with one ofxandyaMatrixand the other a traditional matrix orvector now treats the unclassed argument as a.geMatrix.dimnames(solve(x))is nowrev(dimnames(x))fordenseMatrixx, consistent with the handling ofdimnamesbysolve.default. Methods forsparseMatrixxhave not been addressed (yet).
Memory
In many more (but not yet all) places, Cfunctions protect the values of
R_do_slot,Rf_getAttrib,Rf_mkString, etc. from garbagecollections, squashing many new and some oldrchkwarnings.
New Features
is.nan(x)is now implemented for allxinheriting from virtual classMatrixorsparseVector.Diagonal(n=, x=)now recyclesxof anypositive length to lengthn. Previously, recycling wassupported only forxof length 1.Products involving
diagonalMatrixorindMatrixhave been broadly improved as follows:dimnames(A %*% B)is now alwaysc(dimnames(A)[1], dimnames(B)[2]).t?crossprod()methods involvingindMatrixorits subclasspMatrixgain aboolArithargument.Numeric and boolean products are always returned as
dMatrixandnMatrix, respectively, except in a fewspecial cases where the product can be represented as anindMatrix. (Previously, coercions were skipped when oneof the operands was unit diagonal.)Products of
diagonalMatrixwith densetriangularMatrixnow correctly give atriangularMatrixresult (and without unpacking).Products of
diagonalMatrixwith[RT]sparseMatrixnow preserve storage, no longer coercingtoCsparseMatrix.crossprod(x, y)no longer requires the product ofncol(x)andncol(y)to be less than2^31when bothxandyareindMatrix. (The newimplementation now always gives adgTMatrixresult,whereas previously the result would typically but not always beadgCMatrix.)
kronecker(<Matrix>, <Matrix>)now gives the correct“shape” (general, [unit] triangular, symmetric, diagonal)in all cases where it can be known without checking.kronecker(<[CR]sparseMatrix>, <Matrix>)now retainsthe storage of the first argument, no longer coercing toTsparseMatrix.New exported functions
dimScale,rowScale, andcolScale, for scaling rows and columns of a[mM]atrixwithout losingdimnamesand whereappropriate without losing symmetry.
Changes in version 1.5-1 (2022-09-12, svn r3642)
Memory
ASan-detected memory bugs are fixed in Cfunctions
Tsparse_as_CRsparseandpMatrix_validate.The former was triggered by.T2C(<0-by-0>)and the latterwas triggered byas(<length-10000 integer>, "pMatrix").
Changes in version 1.5-0 (2022-09-09, svn r3636)
Deprecated and Defunct
With a few exceptions, direct coercions to non-virtualsubclasses of
Matrix(e.g.,dsCMatrix) have beenformally deprecated. For now, these will continue to work asbefore, but with a warning indicating how to accomplish thedesired coercion via virtual classes (e.g.,symmetricMatrix) alone. How such warnings are signaled iscontrolled by the global optionMatrix.warnDeprecatedCoerce.0or lessis to be silent.
1is to signal a warning with each deprecatedcoercion.
2or greateris to signal an error with eachdeprecated coercion.
NAis to signal a message or warning (see below)with the next deprecated coercion and be silent after that.
If unset or invalid, then the value of the environment variableR_MATRIX_WARN_DEPRECATED_COERCE (
NAif unset) isused. This is cached when theMatrix namespace isloaded.
Option values are coerced to integer before use.
To reduce disruption to existing code, theNAcase signalsmessages rather than warnings with coercions to the most-usednon-virtual subclasses ofMatrix, namelydg.Matrixandd.CMatrix. This may change in the future.
Classes
New virtual class
unpackedMatrixrepresenting densematrices in unpacked format. It extendsdenseMatrixand isextended by[nld](ge|sy|tr)Matrix, i.e., the subclasses ofdenseMatrixnot extendingpackedMatrix.The validity method for
dppMatrixrequiresnon-negative diagonal elements, matching the validity method fordpoMatrix.The validity method for
Matrixtolerates vector typesother than"character"forDimnames[[i]].
Bug Fixes
Symmetrization of
<Matrix>@Dimnamesanddimnames(<matrix>)now goes through C utilitysymmDN()in most places, resolving some earlierinconsistencies.Many more validity methods now correctly operate under theassumption that methods for superclasses have already been called,eliminating many redundant checks.
Validation of
<Matrix>@Dimnow looks at typebefore length, avoiding a misleading error message.Validation of
<Matrix>@Dimnamesnow avoidsisNewList, which had allowed an error message suggestingthatNULLis a list.Setting a factor on a
compMatrixis now to installthe factor itself, not a copy, for efficiency and consistency withthe semantics of<compMatrix>@factors[[name]] <- value.Long vector support in methods for packing and unpacking
denseMatrix, and others.diag<-incorrectly preserved the class of densematrices, so that, e.g.,`diag<-`(x=<dpoMatrix>, value=-1)was still adpoMatrix. Now the result is always one of themore general.(ge|tr|sy|tp|sp)Matrix.t(<corMatrix>)no longer clears thesdslot.t(<p?BunchKaufman>)now returns one of the more generaldt[rp]Matrix, rather than preserving class and clearing thepermslot.t(<symmetricMatrix>)no longer reverses theDimnamesslot. Symmetrization ofdn <- x@Dimnamesandt(x)@Dimnameshad given different results whendn[[1]]anddn[[2]]were non-NULLandasymmetric.isTriangular(x, upper)had incorrectly returnedFALSEforxof classtriangularMatrixwhenupper = TRUEandx@uplo = "L"or whenupper = FALSEandx@uplo = "U".isTriangularis nowequivalent toisDiagonalin those cases.isSymmetric()was equivalent toisDiagonal()for triangular matrices,not allowing numerical fuzz via anargumenttol. Atolargument is now implemented forall subclasses ofdMatrixexcept for those inheriting fromsymmetricMatrixordiagonalMatrix.Methods for
isSymmetricnow also look atDimnamesandnames(Dimnames), followingisSymmetric.matrixfrombase. See also New Features.band(x, -k, k)for sparsexusedisSymmetric(x)(which tolerates numerical fuzz) to test forsymmetry, resulting in loss of information in some cases. Now ittests thatxinherits fromsymmetricMatrix, and soreturnssymmetricMatrixin fewer cases.triu(x, k)andtril(x, k)incorrectly requiredk <= m(instead ofk <= n), form-by-nsparsex. They now accept allkfrom-mton, with fewer errors in them < ncase.crossprod(<Rsparse>, <Tsparse>)and similar now workagain (optionalboolArithwas not passed on), fixingMatrixPR#6766 by David Cortes. Ditto fortcrossprod(), wherethe old result was even wrong when it had “worked”, beforeMatrix 1.2-0.as(<matrix>, "nMatrix")can now be sparseordense, going viaMatrix(), for greater consistency withcoercions todMatrixandlMatrix. (Previously, theresult was always anngTMatrix.)forceSymmetric(<[RT]sparseMatrix>)are now moreefficient, returning symmetric[RT]sparseMatrixwithoutintermediate coercions toCsparseMatrix.tcrossprod(a, b)for unit triangular sparse matricesnow works correctly.!<ltrMatrix>is no longer an error in the 0-by-0 unitdiagonal case.Coercions among
[CRT]sparseMatrixpreserve thefactorsslot in more cases.Coercions of overallocated
l.TMatrixtodenseMatrixorCsparseMatrixnow giveTRUEinstead ofNAin theNA || TRUEcase, followingconventional logic.Methods for unpacking and indexing
packedMatrixandfor coercing from[CRT]sparseMatrixtodenseMatrixnow check more consistently for overflow ofR_XLEN_T_MAX.solve(<ddenseMatrix>, <ANY>)is removed from themethod list. It had allowed infinite recursion, e.g., withsolve(new("dgeMatrix"), NULL).is.na(<ndenseMatrix>)gaveTRUEwhere thexslot hadNA. Now the result is always a zeromatrix.is.na(<.t[rp]Matrix>)andis.infinite(<.t[rp]Matrix>)ignored thediagslot,behaving always as thoughdiag == "N". They now giveFALSEon the diagonal in thediag != "N"case.Now only “nontrivial” matrix elements determinewhether
is.na(<denseMatrix>)is anndenseMatrixorannsparseMatrix.is.na(<ddenseMatrix>)coerced tolMatrix.This unnecessary step is avoided now, saving a potentiallynontrivial allocation.solve(<ddenseMatrix>, b)coerced the first argumenttodgeMatrixwhenbwas not addenseMatrixortraditionalmatrix. This unnecessary step is avoided now,so that specialized methods ford(tr|sy|po|tp|sp|pp)Matrixare used where possible (including forbinheriting from[ln]denseMatrix,sparseMatrix, ornumLike).`dim<-`(x, -x@Dim)is now an error, no longeryielding an invalidMatrixobject.`dim<-`(x, x@Dim)is now faster, returningxwithout allocation in all cases.`dim<-`(x, value)gives a better error whenvaluecontainsNAor elements exceedingINT_MAX.`dim<-`(<RsparseMatrix>, value)is now anRsparseMatrix, rather than aTsparseMatrix.For consistency with other methods,
symmpart(<diagonalMatrix>)now always inherits from bothdMatrixandsymmetricMatrix, andskewpart(<diagonalMatrix>)now always has symmetricDimnames.Zeros on the diagonal of
skewpart(<[CRT]sparseMatrix>)are nowstructural.as(<ndenseMatrix>, "(vector|matrix|[dl]Matrix)")andnnzero(<ndenseMatrix>)now correctly treatNAin thexslot asTRUE.as(<[nl].TMatrix>, "dMatrix")now correctly handlesthe overallocated case: data for each unique[i,j]pair areaggregated logically (x1 || ... || xn) rather thanarithmetically (x1 + ... + xn), so that elements of theresult are restricted to the setc(0, 1, NA). This bug hadalso affected the result ofsum(<[nl].TMatrix>).dimnames(as(x, "matrix"))is nowNULLforallxinheriting fromMatrix, whenx@Dimnamesis the triviallist(NULL, NULL)..bdiag(<named list>)no longer propagates names totheDimslot of the result.as(<named vector>, "denseMatrix")now correctlypropagatesnamesto the result.as(<d.[CR]Matrix>, "lMatrix")no longer dropsnon-structural zeros, for greater consistency with analogouscoercions.Matrix(x, doDiag)now behaves as documented fordiagonal matricesxwith asymmetricdimnames,returning adiagonalMatrixwhendoDiag = TRUE,rather than atriangularMatrix.Matrix(<n-dimensional table>) now works for
n != 2.Matrix(<sparseVector>)now works for vector lengthsother than 1, no longer giving an error about length mismatch whenneither ofnrowandncolare supplied.Matrix(<diagonalMatrix>, doDiag = FALSE)is now asymmetricMatrix, not adiagonalMatrix, matching thedocumentation ofdoDiag.Matrix(<.geMatrix>, sparse = TRUE, forceCheck)andMatrix(<.g[CRT]Matrix>, sparse = FALSE, forceCheck)nowrespectforceCheck = FALSEby always returninggeneralMatrix, i.e.,not testing for symmetric ortriangular structure.Matrix(0, nrow, ),Matrix(0, , ncol)now throw(correct) errors fornrow,ncolin the interval[0,1), consistent withbase::matrix().sparseDefault(<sparseMatrix>)now counts zeroswithout coercing tomatrix, makingMatrix(<sparseMatrix>, sparse = NULL)much more efficient.Methods for group generic
Mathno longer preservex@diag == "U"or losex@Dimnameswhenf(0) == 0andf(1) != 1. (The former happened fortriangularMatrixxand the latter fordiagonalMatrixx.)image(Z)for a completely “empty” (all 0)sparseMatrixworks again (?!).x[i, ] <- valueandy[, j] <- valueis now anerror in more cases form-by-0CsparseMatrixxand 0-by-nCsparseMatrixy. Inthese cases, subassignment gave a (formally) invalid result.chol(<ds[yp]Matrix>)now calls the underlying C-levelroutine exactly once. Previously, it was called an extra time inorder to test for positive definiteness, with the result thrownaway (!). Hence these methods should become approximately twotimes faster.dimnames(chol(x))is identical todimnames(x)in all cases, now even whenchol(x)is constructed from acachedMatrixFactorization, for greater consistency withbase::chol.default().chol(<generalMatrix>)no longer looks atDimnameswhen testing for symmetry.lu(<dtCMatrix>)no longer returns an invalidsparseLUobject in the lower triangular case.lu(x)had sometimes incorrectly cached its returnvalue as element"lu"(rather than"LU") ofx@factors. Now it is always"LU".Compareoperators, e.g.,a > b,x != y, now work correctly in more dense unitriangular and sparse0-extent cases.!<nMatrix>is now always annMatrix, never anlMatrix.!<ndenseMatrix>andwhich(<ndenseMatrix>)nowcorrectly handleNAasTRUE.anyNA(<denseMatrix>)had incorrectly returnedanyNA(.@x)in many cases, giving false positives for some.(tr|sy)MatrixandndenseMatrix. Now methodsrespect the “rules” of these classes.The boolean arithmetic product
A %&% Band e.g.,crossprod(A, B, boolArith=TRUE)now should behave as ifdrop0(A)anddrop0(B)were used, i.e., for formallysparse matrices, the boolean product results should be stable withrespect to non-structural vs structural zeros.t(<symmetricMatrix>)now retains thefactorsslot, avoiding recomputation.Fixed the (quitelong standing)MatrixPR#6777, reportedby Manuel Koller:
tcrossprod(<matrix>, <[dln]sCMatrix>)hasbeen wrong in some cases.
Memory
qr(<big sparse>)could segfault due to integeroverflow inside ofcs_multiply. Now an error is signaledindicating “out of memory”. Reported by Benjamin TynerasMatrixPR#6610.Valgrind warning originating in
cholmod_sdmultis squashed. Reported by David Cortes asMatrixPR#6726.
New Features
KhatriRao()gets newsparseY = TRUEoption andalso works for moreMatrixclasses.Virtual class
packedMatrixgains methods forpack,unpack,isSymmetric,isTriangular, andisDiagonalimplemented in C,replacing those defined for many subclasses individually.Virtual class
unpackedMatrixgains methods forpack,unpack,isSymmetric,isTriangular,isDiagonal,t,diag, anddiag<-implemented in C, replacing those defined for manysubclasses individually.isTriangularandisDiagonalare nowimplemented in C also for[CRT]sparseMatrixandstandardmatrix.isSymmetricis now implemented inC for alldenseMatrixand all[CRT]sparseMatrix, though these C routines arecurrently only called when testing forexact symmetry(always for[ln]Matrix, only whentol = 0fordMatrix).Methods for
isSymmetricgain an argumentcheckDN = TRUEindicating whether symmetry ofDimnamesshould be checked. For backwards compatibilityand consistency withisSymmetric.matrixfrombase,the actual condition ischeckDN && check.attributes.isTriangular(x, upper)now has akindattributeif and only ifxis triangular andupperisNA.diag(<unpackedMatrix>) <- valuenow behaves likediag(<packedMatrix>) <- value, supporting coercionsdepending ontypeof(value), consistent withdiag<-frombase.packandunpackare now identity functions forpackedMatrixandunpackedMatrixarguments,respectively (previously an error).pack(<.geMatrix>)(previously an error) now behaves aspack(<matrix>), i.e.,by checking for symmetry or triangularity before packing.unpack(<matrix>)now works and is equivalent toas(<matrix>, "unpackedMatrix"), with result inheriting from.(ge|tr|sy)Matrix, as appropriate.Many more validity methods implemented in C, for efficiency,including methods for
Matrix,compMatrix,diagonalMatrix,indMatrix,pMatrix,corMatrix,[liz]Matrix, andndenseMatrix.band(x, k1, k2)is optimized further for both denseand sparsex, returningtriangularMatrix,symmetricMatrix, andpackedMatrixin more cases.band()is now implemented also fordiagonalMatrix(onlytri[ul]()worked before).Coercions
.ge<->.g[CRT],.t[rp]<->.t[CRT],.s[yp]<->.s[CRT], and..[CRT]<->matrixare now fullyimplemented and optimized, with minimal intermediate allocations.These (and others) no longer rely on CHOLMOD, which had handledinteger types as double and required preprocessing in many cases(withdiagU2N(), etc.).Fixes in group methods (e.g.,
>,&,|),notably for matrices inheriting from classsymmetricMatrix,triangularMatrix,lMatrix, ornMatrix.as.vector,as.numeric, andas.logicalare now implemented for allMatrix.Subassignment to
indMatrixis no longer prohibited,now going viaTsparseMatrix.indMatrixgains methods forisTriangular,isDiagonal,diag,diag<-,band,tri[ul], andforceSymmetric. It also gainscoercions to more virtual classes (notablydenseMatrix) anda coercion topMatrix.solve(<ddenseMatrix>, <numLike>)now works in allcases.determinant(<ds[yp]Matrix>)is now much faster in thepositive definite case, no longer going viadgeMatrix.diag(<[CRT]sparseMatrix>)is now done in Cand is highly optimized in the.[ts][CR]Matrixcase.symmpartandskewpartare now done inC for alldenseMatrixand all[CRT]sparseMatrix. Both now more faithfully preserve the“storage” of their argument. (Previously,symmpart(<packedMatrix>)was anunpackedMatrix, and(symm|skew)part(<[RT]sparseMatrix>)was aCsparseMatrix.)as(<vector|matrix>, "([dln]?dense|[dlnCRT]?sparse)Matrix")are now fully and moreconsistently implemented. In the vector case, the result is nowalways alength-by-1generalMatrix. In the matrixcase, structure is now always examined, hence the result is asymmetricMatrixortriangularMatrixin more cases.Matrix(<classed matrix>)now works for classesother thantable.lu(<dt[rpCRT]Matrix>)andlu(<ddiMatrix>)nowbehave more consistently. In the diagonal, upper triangular, andunit lower triangular cases, the result is obtained“directly”, i.e., without pivoting. In the non-unit lowertriangular case, it is obtained with pivoting. (Previously,pivoting was never done fordtCMatrixand always done fordt[rpRT]MatrixandddiMatrix.)lu(x)now caches its return value also for allds.Matrixx(by default).readMM()now warns if the number of entries found isless than number reported in the header.x[i]now works fornMatrixi, just asforlMatrixi. This supports constructions such asx[is.na(x)], where the logical operation produces annMatrixbecause it is neverNA.
Misc
AZERO()and friends gain an argument specifying azero constant (0 forintarrays, 0.0 fordoublearrays).C-level utilities
(R_)?[gs]et_factors()have beenrenamed(R_)?[gs]et_factor(), as they only ever get and setone factor.The signature of
set_factor()has been changed tomatch otherset*()functions: to(object,name,value)from(object,value,name).For clarity,
set_factor()now returnsvoidandis used like otherset*()functions (i.e., for its sideeffect). TheR interface is unchanged:R_set_factor()continues to return the value being set.C-level utilities
make_[di]_matrix_(triangular|symmetric)(),packed_to_full_(double|int)(),full_to_packed_(double|int)(), andinstall_diagonal(_int)?()are replaced by safer, moreconsistently named ones. Previous versions allowed integeroverflow.C-level utilities
dup_mMatrix_as_d?geMatrix()arereplaced by the more generaldense_as_general(), whichtakes arguments controlling memory allocation and the“kind” of the.geMatrixresult.New C-level utility
DimNames_is_symmetric()withRinterfaceisSymmetricDN(), which should be usedconsistently to test for symmetry of[dD]imnames. Notethat these are intended to behave consistently withsymmetricMatrix_validate(), by allowing, e.g.,list(NULL, nms), but not, e.g.,list(A = NULL, B = nms).Coercions to
triangularMatrixandsymmetricMatrixare now almost all inherited fromMatrix, whose methods simply calltri[ul]()andforceSymmetric()ifisTriangular()andisSymmetric(), respectively, returnTRUE.Many of the exported
.*2*utilities have beenredefined as aliases or wrappers of new, more general functions(see below). These not-yet-deprecated functions have beencentralized in ‘R/denseMatrix.R’ and ‘R/sparseMatrix.R’.New C-level utilities
R_(dense|sparse)_as_kind()for coercion from one “kind” to another;R_(dense|sparse)_as_general()for coercion from triangular and symmetric to general;R_(dense|sparse)_band()for coercion to triangular (and other banded);R_(unpacked*|packed*|sparse)_force_symmetric()for coercion to symmetric;R_(dense|sparse)_as_(sparse|dense)()for coercion between dense and sparse of the same “kind”and “structure”;R_diagonal_as_sparse()for coercion fromdiagonalMatrixto any[CRT]sparseMatrix;R_(dense|sparse|geMatrix)_as_(matrix|vector)()for coercion to base matrix and vector; andtCRsparse_as_RCsparse()for the idiomsas(t(<[CR]sparseMatrix>), "[RC]sparseMatrix").These all have not-yet-exportedR wrappers.indTri()andindDiag()now in C, with a newargumentpackedfor efficiently indexingpackedMatrix.indDiag()now behaves sensibly in then = 0case..M.kind(),.M.shape(), and (new).M.repr()are now done in C viaR_check_class_etc(), requiring a class definition only in“rare” cases.
Changes in version 1.4-1 (2022-03-21, svn r3446)
Installation
Some warnings surfaced by-Wconversion aresquashed.
Compatibility
tryInvokeRestartis defined forR<4.0.0.Thanks to Michael Chirico for the report.
SuiteSparse
The patch for header‘SuiteSparse_config/SuiteSparse_config.h’is improved for Windows.
Classes
New virtual class
packedMatrixrepresenting densematrices in packed format. It extendsdenseMatrixand isextended by[nld](sp|tp)Matrix.
Memory
Protection stack imbalances detected by
rchkarefixed.
Bug Fixes
diag(x)methods now mostly also keepnamesfromdimnames(x)by default and obeynames=*moregenerally.
New Features
Methods for subscripting
packedMatrix, includingdiag(), notably keeping names by default and fort()which are memory efficient, i.e., do not work via unpacking,thanks to Mikael Jagan.New
dmperm()implementing a Dulmage-Mendelsohndecomposition, thanks to the persistency of Mauricio Vargas(@uc.cl).Export more low-level conversion utilities:
.n2dgT,.m2ngCn,.m2ngTn.Provide some matrix multiplication methods for
RsparseMatrix.
Misc
Our C sources now use
R_Calloc(),R_Free()etc, instead of the shorter versions without'R_'. Consequently, we get closer toSTRICT_R_HEADERS.Also, include<float.h>forDBL_EPSILON.Modified
AZERO()to work withR_xlen_tand newAZEROs()forsize_t.
Changes in version 1.4-0 (2021-12-08, svn r3419)
Compatibility
‘inst/test-tools-1.R’:
Sys.memGBreturnsNA.value = 2.10201on Windows, no longer callingmemory.limitwhich is a stub sinceR version 4.2.0.
Memory
Several low level functions are adjusted to avoid integeroverflow in
i+j*mor similar. Reported by Dario Strbenacon the R-devel mailing list (“dgTMatrix SegmentationFault”, June 10, 2021).Leak in
as(<dtCMatrix>, "denseMatrix")when theargument is unit triangular is fixed. Thanks to Bill Dunlap forthe report and patch inPR#18204.Leak in
crossprod(<dsCMatrix>)is fixed. Thanks toBill Dunlap for the report and patch inPR#18205.Leaks in
solve(<dgCMatrix>, <ddenseMatrix>)andlu(<dgCMatrix>)and when the argument is near-singular (orwhen memory is exhausted) are fixed. Thanks to Bill Dunlap forthe report and patch inPR#18206.Leaks in
[cr]bind2(x, y)when both arguments aresparse and exactly one is nonzero pattern are fixed. Thanks toBill Dunlap for the report and patch inPR#18210.solve(<dsCMatrix>, ...)restarts after catchingwarnings signaled fromdsCMatrix_*_solveso that memory isfreed rather than leaked. Thanks to Bill Dunlap for the reportand patch inPR#18214.
Bug Fixes
sparse.model.matrix(.., contrasts.arg = <.. ddiMatrix ..>)now works correctly, fixingMatrixPR#6673 by Davor Josipovic.sparse.model.matrix(..)now also works in cases thecontrast matrix has become adenseMatrix; e.g., in a caseusingpoly(.)in the formula; now works correctly, fixingMatrixPR#6657 and useful suggestions by Nick Hanewinckel.Fixed the internal
attr.all_Mat()auxiliary forall.equal(), notably for the case when exactly one of thematrices is a basematrix.Fixed long-standing bug in the
rbind2()method forlogical dense matrices, specificallylgeMatrix, thanks tothe notice by Aaron Lun.band(M, k1, k2)now also works whenk1 * k2islarger than 2^31-1, the maximal integer, fixingMatrixPR#6743 byAriel Paulson. Further, it works whenMis a sparsesymmetricMatrixbut the band is not symmetric,k1 != -k2.sparseVector(i=integer(), length=2^33)now doesshow/print, after fixing a bug in thehead()method forempty sparseVectors. Reported by David Cortes asMatrixPR#6745.ss <- <sparseVector>[i]gave an invalid sparseVectorssasss@iwas not necessarily sorted; thanks to areport by Quran Wu.as(<dsyMatrix>, "generalMatrix")and similar,sometimes didnot use (C-level)symmetric_Dimnames()etc; report (toR'sPR#18250 by Mikael Jagan); fixed all on Clevel. As a consequence, you will now seemore preserveddimnames after matrix transformations or operations which involvedsymmetric matrices.as(<ddiMatrix>, "matrix")no longer loses dimnames,thanks to Mikael Jagan's report asMatrixPR#6751.
Misc
No longer include ‘Rdefines.h’ as it is somewhatdeprecated.
Changes in version 1.3-4 (2021-05-24, svn r3392)
Compatibility
Tests are further revised for length mismatch warning in
matrix(data, nrow, ncol)underR\ge4.2.0.
Changes in version 1.3-3 (2021-05-01, svn r3390)
Installation
Matrix
\ge1.3-3 depends onR\ge3.5, relaxing the dependency onR\ge3.6 introduced inMatrix version 1.3-0.
Compatibility
Tests are revised for length mismatch warning in
matrix(data, nrow, ncol)underR\ge4.2.0.
C-Level API
‘inst/include/cholmod.h’ and‘inst/include/Matrix_stubs.c’ needed adjustment after theSparseSuite update inMatrix version 1.3-0.MatrixPR#6714reported by Kasper Kristensen, who maintainsTMB.
Deprecated and Defunct
cBind()andrBind()are now defunct: simplyusecbind()andrbind()instead.
Classes
Class unions
MnumericandnumericVectorsareremoved. These were unexported and unused but nonethelessvisible to users, appearing as superclasses of many basic classes.Notably, a proposed change to the validity method forMnumericwould have broken classfactor, whichextendedMnumericbut would not have been valid under theproposal.
Bug Fixes
Fixed a thinko (in 1.3-2): Now direct coercion from
ddiMatrixtodgCMatrix, and hence, e.g.,as(Matrix(1, sparse=TRUE), "dgCMatrix") now works.Fixed error message in <dtrMatrix> multiplication.
Fixed long-standing bug in
R[,j] <- vwhenRis anRsparseMatrix,MatrixPR#6709 by David Cortes.as.matrix()andas.array()now work forsparseVectoras expected; seeMatrixPR#6708.M[,](and similar) now work as in baseR;MatrixPR#6720 by David Cortes.-Snow works also whenShas nofactorsslot. It signalled an error, e.g., for sparse triangular matricesS;MatrixPR#6656, reported by Chun Fung (Jackson) Kwok.M*2and similar no longer keep cached factorizations(in 'factors' slot), but drop them via internal new.empty.factors().MatrixPR#6606, reported by Thomas Lumley.removed a few duplicated
.alias{.}from‘man/*.Rd’.
Misc
translation updates (of outlines only); finally addedItalian (by Daniele Medri) to svn; updated French (by PhilippeGrosjean), forgotten (R part of) Korean. New Lithuaniantranslations by Gabriele Stupuriene & Rimantas Zakauskas.
In internal
diagOdiag()method, no longer usematrix(x, n,n)whenxis longer than n*n.Eliminating the need for ‘ftp://*’, add the very small
jgl009MatrixMarket example to our ‘external/’ files.
Changes in version 1.3-2 (2021-01-05, svn r3362)
Installation
USE_FC_LEN_Tis defined before ‘Rconfig.h’ isincluded. UnderR\ge3.6.2, the effect is thatFC_LEN_Tis defined when ‘R_ext/BLAS.h’ is included,and the result is that ‘R_ext/BLAS.h’ definesFCONEas a nonempty value suitable for passing character lengths fromC to Fortran.
Memory
matrix_trfprotects two more objects from garbagecollection, squashing tworchkwarnings.
Bug Fixes
rankMatrix()tweaks for the singular values basedmethods, notablymethod = "maybeGrad".as(new("dtCMatrix", diag="U"), "matrix")now works,as C-leveldiagU2N()now also works for 0-dimensionaltriangular matrices; this also fixes a subsetting(“indexing”) bug of such 0-dimensional matrices, thanks toa report by Aaron Lun.logical subsetting of 0-dim. (diagonal/triangular) matricesfixes.
chol(<diagonal dt[CRT]Matrix>)now works.
Changes in version 1.3-1 (2020-12-23, svn r3352)
Bug Fixes
rankMatrix(<dense>, method="qr.R")no longer assumesnon-negative diagonal entries of theRmatrix.
Changes in version 1.3-0 (2020-12-15, svn r3351)
Installation
Matrix
\ge1.3-0 depends onR\ge3.6.Macro
FCONEis defined and used to pass characterlengths from C to Fortran underR\ge3.6.2 (without breaking installation under olderR). Thanksto Brian Ripley.
SuiteSparse
The internal SuiteSparse library sources are updated fromversion 4.2.1 to version 5.7.1. The change is visible in
.SuiteSparse_version().
Significant User-Visible Changes
Matrix(*, doDiag=TRUE)wheredoDiag=TRUEhasalways been the default is now obeyed also in the sparse case, asalldiagonalMatrixare alsosparseMatrix.Matrix(0, 3,3)returns addiMatrixinstead of adsCMatrixpreviously. The latter is still returned fromMatrix(0, 3,3, doDiag=FALSE), and e.g.,.symDiagonal(3,pi).
Also a triangular matrix, e.g.,dtrMatrixis detected nowin cases withNAs.
This is both a bug fixand an API change which breaks codethat assumesMatrix(.)to return aCsparseMatrixin cases where it now returns adiagonalMatrix(whichdoes extendsparseMatrix).
New Features
Subassignment to
diagonalMatrixnow returns sparsetriangularMatrixmore often; also (sparse)symmetricMatrix.nearPD()gets new option: Ifbase.matrix = TRUE, the resultingmatcomponent is abasematrix, as often used desired whennearPD()is usedoutside theMatrix package context.Factored out new
qr2rankMatrix()utility fromrankMatrix().New
BunchKaufman(<matrix>)method.Added
wrld_1degsparse matrix example todistributed version ofMatrix (no longer excluding itvia ‘.Rbuildignore’).New (simple)
mat2triplet()function to be usedinstead ofsummary(<sparseMatrix>)in code.Internal
.diag2tT()gains new optiondrop0 = TRUEand hence now by default drops zero diagonal entries.Consequently, e.g.,as(<diagonalMatrix>, "CsparseMatrix")now drops such zeros, too.sparseMatrix()gets new argumentrepr = "C",superseding the (now deprecated)giveCsparse = TRUE.Allows to returnRsparseMatrix.Similarly,
rsparsematrix(),fac2sparse()andfac2Sparse()get the newreprargument and theirgiveCsparseis deprecated, sometimes only informally fornow.sparse.model.matrix()gets optionsep = "",with, e.g.,sep = ":"allowing to get easier column names;fromMatrixPR#6581, by Vitalie Spinu.
Memory
The second argument in calls to
cholmod_factorize_pfrominternal_chm_factorwas a pointer to 1doubleinstead of adoublearray of length 2, resulting in bufferoverflow there.
Bug Fixes
rankMatrix(<sparse>, method="qr")now returnsNA(orNaN) instead of signalling an error in thecase the sparseQ Rdecomposition gaveNAs indiag(R).Coercion (
as(., .)) from e.g.,lsyMatrixtoCsparseMatrixsilently made asymmetric dimnamessymmetric, as did theinternalforceCspSymmetric(*, dimNames)which may be called fromforceSymmetric().MatrixPR#6659, reported by Georg Kindermann:
<sparseVector>[i] <- valbug is fixed.MatrixPR#6666, reported by Ezra Tucker:
which(<ldiMatrix>, array.ind=TRUE)thinko is fixed.For R-devel Dec 4, 2020: adapt all.equal() check of sparsematrix images (which contain panel functions with environments).
Changes in version 1.2-18 (2019-11-26, svn r3300)
Compatibility
‘inst/test-tools-1.R’: a bug-fixed
canCoerceis used underR<3.6.2.
Memory
ddense_skewpartprotects another object from garbagecollection, squashing a remainingrchkwarning.
Bug Fixes
as(m, "dgTMatrix")does not losedimnamesanymore whenmis a (traditional)matrix.M[logical(0), ]now has dimension0 x kforsparseMas for base matrices.log(M, base)(the 2-argument version oflog())wrongly gave the result forbase = exp(1), i.e., the1-argument default.‘test-tools-Matrix.R’:
Qidentical()no longerassumesclass(<matrix>)to be of length 1.
Changes in version 1.2-17 (2019-03-20, svn r3294)
Compatibility
isFALSEis defined forR<3.5.0.
Memory
C functions protect more objects from garbagecollection, squashing several
rchkwarnings.
Changes in version 1.2-16 (2019-03-04, svn r3291)
New Features
regression tests depending on
sample()now are futureproof reproducible, viaRNGversion(.).give information about #{rows} and #{columns} that aresuppressed in print()ing if the matrix is larger than
max.print.
Bug Fixes
data(<Matrix-data>)no longer attachesMatrixto the search path.Opsgroup methods, i.e.,Arith,Compare,Logic, now should all work with 0-extentmatrices as well, thanks to bug reports by Aaron Lun, Universityof Cambridge.when printing and formatting sparse matrices, see
formatSpMatrix(), themaxpoption, e.g., fromgetOption("max.print"), is “rounded up” to 100, asvery small values are very rarely appropriate.
Changes in version 1.2-15 (2018-08-20, svn r3283)
New Features
image()gets new optional argumentborder.color.
Bug Fixes
image(Matrix(0, n,m))now works.
Changes in version 1.2-14 (2018-04-08, svn r3278)
New Features
German translation updates.
Memory
dgCMatrix_cholsolprotects one more object fromgarbage collection, squashing anrchkwarning.
Changes in version 1.2-13 (2018-03-25, svn r3275)
New Features
Faster
as(<matrix>, "sparseMatrix")and coercion todgCMatrix,ngCMatrix, etc, via new directCmatrix_to_Csparse()which doesnot goviadgeMatrix. This also works for large matricesm, i.e., whenlength(m) >= .Machine$integer.max.Also provide low-levelR functions
.m2dgC(),.m2lgC(), and.m2ngC()for these.
Memory
C functions protect more objects from garbagecollection, to be “rather safe than sorry”. Thanks toTomas Kalibera's
rchktools.
Bug Fixes
cbind(NULL,<Matrix>)no longer returnNULL;analogously forrbind(),rbind2(),cbind2(),fixing very long standing typo in the corresponsingcbind2()andrbind2()methods.The deprecation warning (once per session) for
cBind()andrBind()finally works (fixing a simplethinko).cbind()andrbind()for largish sparsematrices no longer gives an error because of integer overflow (inthe default case wheresparseis not been specified henceis chosen by annzero()based heuristic)..symDiagonal(5, 5:1)and.trDiagonal(x = 4:1)now work as expected.Sp[i]now is much more efficient for large sparsematricesSp, notably when the result is short.<sparseVector>[ <negative integer> ]now also givesthe correct answer when the result is “empty”, i.e., allzero or false.large
dspMatrixanddtpMatrixobjects cannow be constructed vianew(*, Dim = *, x = *)also whenlength(x)is larger than 2^31 (as the C internalvalidation method no longer suffers from integer overflow).
Changes in version 1.2-12 (2017-11-10, svn r3239)
New Features
crossprod(x,y)andkronecker(x,y)have becomeconsiderably more efficient for largeindMatrixobjectsx, y, thanks to private nudging by Boris Vaillant.
Bug Fixes
MatrixPR#6185:
c < 0now also works for derived sparseMatrices (which onlycontain Matrix classes); via improvinghiddenMatrixClass(). Part of such derived matrices onlywork inR\ge3.5.0.using
Authors@Rin ‘../DESCRIPTION’ to list allcontributors.solve(-m)no longer should use a cached Choleskyfactorization (ofm).
Changes in version 1.2-11 (2017-08-10, svn r3225)
Compatibility
length(<NULL>) <- valueis avoided as it isdeprecated inR\ge3.5.0.
New Features
S4 method dispatch no longer emits ambiguity notes (bydefault) for everybody, apart from the package maintainer. Youcan reactivate them by
options(Matrix.ambiguityNotes = TRUE)
Bug Fixes
rankMatrix(<matrix of all 0>)now gives zero for allmethods, as it should be.qr.coef(<sparseQR>, y)now finally has correct (row)names (from pivot back permutation)..trDiagonal()utility is now exported.
Changes in version 1.2-10 (2017-04-19, svn r3216)
Memory
C functions protect more objects from garbagecollection. Thanks to Tomas Kalibera's
rchktools.
Changes in version 1.2-9 (2017-03-08, svn r3211)
New Features
Opsbetweentable,xtabs, and ourmatrices now work.as(matrix(diag(3), 3, dimnames=rep(list(c("A","b","c")),2)), "diagonalMatrix")@xis no longer named.norm(x, "2")now works as well (and equivalently tobase::norm).sparseVector()now also works withoutxargument.c.sparseVector()method forc()ofsparseVectors (and available as regular function on purpose).
Bug Fixes
as(Diagonal(3), "denseMatrix")no longer returns anon-denseddiMatrix.S[sel,] <- valueand similar no longer segfault, butgive a"not (yet?) supported"error for sparse matricesSand logicalselwhenselcontainsNAs.The same error (instead of a low-level one) is signalled forindexing (with NA-containing logical
sel), i.e.,S[sel,].which(x, arr.ind=TRUE, *)(whenxis alMatrixornMatrix) now works the same asbase::which, obeying an optionaluseNamesargumentwhich defaults toTRUE. Previously, the resultingtwo-column matrix typically had emptydimnames.
Changes in version 1.2-8 (2017-01-16, svn r3201)
Compatibility
Methods for
Opshandle 0-length operands moreconsistently, matching changes planned forR version 3.4.0.
SuiteSparse
SuiteSparse_longis defined asint64_ton allplatforms. Hence we now include C99 header ‘inttypes.h’.The internal CSparse library sources are patched to avoidbuffer overflow in
cs_usolveandcs_utsolvewhenUis singular.
Bug Fixes
x[.] <- valuenow also works forsparseVector, both asxand asvalue.x[FALSE] <- valuenow also works forsparseVector.rep(x, *)now works forsparseVectorandsparse and denseMatrix-classed matricesx.
Changes in version 1.2-7.1 (2016-08-29, svn r3187)
Installation
_POSIX_C_SOURCEis definedconditionally with#ifdef __GLIBC__.
Changes in version 1.2-7 (2016-08-27, svn r3185)
New Features
cBind()andrBind()have been almost silentlydeprecated inR\ge3.2.0 and now give a warning,“once per session” only.bandSparse(*, k=k, *)now returns matrices inheritingfromtriangularMatrixwhen obvious from the diagonalindicesk.
Bug Fixes
KhatriRao(X,Y)now also works whenXorYis completely zero.
Changes in version 1.2-6 (2016-04-27, svn r3175)
Bug Fixes
The 0-dim. Matrix multiplication fix in 1.2-5 did triggerwrong warnings in other diagonal matrix multiplications.
Changes in version 1.2-5 (2016-04-14, svn r3170)
New Features
isSymmetric(m)now also works forindMatrixm.isSymmetric(m)is faster for large dense asymmetricmatrices.
Bug Fixes
Matrix multiplications (
A %*% B) now work correctlywhen one of the matrices is diagonal and the other has a zerodimension.
Changes in version 1.2-4 (2016-02-29, svn r3162)
New Features
sparseMatrix()gets new argumenttriangularand a smarter default fordimswhensymmetricortriangularis true.as(<sparse>, "denseMatrix")now works in more caseswhenprod(dim(.))is larger than2^{31} - 1. Hence,e.g.,!Snow works for much larger sparse matricesS.
Bug Fixes
creating very large dense matrices, e.g., by
as(<sparseM.>, "matrix")would segfault (in case it couldallocate enough storage).
Changes in version 1.2-3 (2015-11-19, svn r3155)
C-Level API
‘inst/include/Matrix.h’ tries harder to define‘alloca’ correctly for compilers that do not define
__GNUC__.
New Features
MatrixClass()is exported now.More exports of semi-internal functions (for speed, named
.<foo>, i.e., inofficial API), such as.solve.dgC.lu().more Korean translations
Bug Fixes
extended
n?CMatrixclasses (e.g., fromsetClass(., contains="ngCMatrix")) now can be coerced viaas(.)tod.CMatrix.The printing of largish sparse matrices is improved, notablyin the case where columns are suppressed, via new
fitWidth = TRUEoption inprintSpMatrix2().cbind2()andrbind2()no longer fail todeterminesparsewhen it is unspecified and henceNA, fixingMatrixPR#6259.
Changes in version 1.2-2 (2015-07-03, svn r3131)
Dependencies
Objects are more systematically imported from “base”packages likestats. It is no longer assumed that thosepackages are attached.
Bug Fixes
Our
colSums(x),rowMeans(y), ..., methodsnow “keep names”, i.e., if the result is a numeric vector,and the matrixxhas column or row names, these become thenames(.)of the result, fixingMatrixPR#6018.
Changes in version 1.2-1 (2015-05-30, svn r3127)
New Features
Matrixnow has aninitialization()methodcoercing 0-length dimnames components toNULLand othernon-NULLdimnames tocharacter. Before, e.g.,numeric dimnames components partially worked, even though it hasalways been documented that non-NULLdimnames should becharacter.as.vector(<sparseVector>)etc, now work, too.lu(<sparseMatrix>)now keepsdimnames.better ‘NEWS.Rd’ (which pleases Kurt and
tidy;-)
Memory
Using
allocato perform large allocations couldoverflow the stack, leading in some cases to a segfault. Nowallocais used only for small allocations. Thanks to areport on the R-help mailing list (“does segfault mean(always) a bug?”, May 5, 2015).
Bug Fixes
S[] <- TandS[] <- spVnow work (in morecases) for sparse matrices S, T and sparseVectorspV.Optional arguments in
image(), e.g.,main=<..>)now also work forlgCMatrix,nMatrixetc; thanks to a 4.5 years old report by MstislavElagin.dimnames(A) <- valnow resets thefactorsslotto empty, as the factorizations now keep dimnames more often.crossprod(<matrix>, Diagonal(<n>))works again (andthese are tested more systematically).Matrix products (
%*%,crossprod, andtcrossprod) fordtrMatrixare correct in allcases, including keeping dimnames.Matrix(d)(and other coercions toMatrix)now correctly keepsdimnamesalso whendis atraditionaldiagonal matrix.
Changes in version 1.2-0 (2015-04-03, svn r3096)
Generic Functions
New generic function
%&%for boolean matrixmultiplication: that is, matrix multiplication using booleanarithmetic.
New Features
New argument
boolArith = NAincrossprod()andtcrossprod().boolArith = TRUEnow forces booleanarithmetic, whereboolArith = FALSEforces numeric one.Several of these products are more efficient thanks to new Cfunctionality based on our newchm_transpose_dense(), andothers based ongeMatrix_crossprod,geMatrix_matrix_mm, etc.Most dense matrix products, also for non-
dgeMatrix,includingl..Matrixandn..Matrixones are nowdirectly handled by new.Call()s.dMatrix(numeric) andlMatrix(logical)matrices can now be coerced tonMatrix(non-zero patternor “boolean”) even when they containNAs, which thenbecomeTRUEs.More thorough checking of
cbind2()andrbind2()methods, notably as they are called fromcbind()andrbind()fromR\ge3.2.0.rbind2(<dense>, <dense>)is faster, being based on new Ccode.symmetric Matrices (i.e., inheriting from
symmetricMatrix) are allowed to havedimnamesofthe formlist(NULL, <names>)and now print correctlyand get correctly coerced to general matrices.indMatrixobject (“index matrices”) no longerneed to be “skinny”.rsparseMatrix()now acceptsrand.x = NULLandthen creates a randompattern matrix(nsparseMatrix).anyDuplicatedT()anduniqTsparse()low levelutilities are exported now.Partial Korean translations of messages.
Deprecated and Defunct
ForR
\ge3.2.0,cBind()andrBind()are deprecated, as they are no longer needed sincecbind()andrbind()do work automatically.
Bug Fixes
Fix some
rbind2()methods.t()now transposes the dimnames even for symmetricmatrices.diag(M) <- valdid not always recyclevaltofull length, e.g., whenMwas adtrMatrix.crossprod(<indMatrix>)was wrong in cases where thematrix had all-zero columns.Matrix products (
%*%,crossprod, andtcrossprod) with one sparse and one dense argument nowreturnnumeric (adMatrix) when they should, i.e.,unless the new settingboolArith = TRUEis applied.
Changes in version 1.1-5 (2015-01-18, svn r3037)
Compatibility
Methods for matrix multiplication (
%*%,crossprod,tcrossprod) are revised to match thebehaviour ofR\ge3.2.0, which better toleratesmatrix-vector products.
New Features
More use of
anyNA()(for speedup).isTriangular()gets new optional argumentupper = NA.
Bug Fixes
crossprod()andtcrossprod()fixes for several<diagonal> o <sparse> combinations.rowMeans(<dgeMatrix>, na.rm=TRUE)was wrongsometimes.fix and speedup of coercions (
as(., .)) from and tosymmetric or triangular matrices.invPerm()coercion to integerdimnames( solve(.,.) )fix [r3036]tril()andtriu()now return correctuplo.names(dimnames(.))now preserved, e.g. insymmpart()or subsetting (A[i,j]).
Changes in version 1.1-4 (2014-06-14, svn r2994)
New Features
new
rsparsematrix()for random sparse Matrices.improved warnings, notably for unused arguments previouslyswallowed into
....
Bug Fixes
crossprod(<vec>, <dsyMatrix>)fixed.crossprod()andkronecker()fixes for some<indMatrix> cases.
Changes in version 1.1-3 (2014-03-30, svn r2982)
New Features
%*%andcrossprod()now also work withsparseVectors.speedup of
crossprod(v, <sparseM>), thanks to nudgeby Niels Richard Hansen.new help page for all such matrix products(‘../man/matrix-products.Rd’).
Bug Fixes
image()now gets correctylimagain.More consistent matrix products.
Changes in version 1.1-2-2 (2014-03-04, svn r2966)
Bug Fixes
correct adaption toR 3.1.0
using
tolerance(and not ‘tol’) inall.equal()
Changes in version 1.1-2 (2014-01-28, svn r2962)
New Features
export fast power-user coercion utilities
.dsy2mat(),.dxC2mat(),.T2Cmat(),..2dge().
Bug Fixes
matrix products now (mostly) work with
sparseVectors;and correctly in some more cases.
Changes in version 1.1-1.1 (2013-12-30, svn r2957)
Installation
Matrix
\ge1.1-1.1 depends onR\ge2.15.2 to ease checking.
Compatibility
‘inst/test-tools-1.R’:
assertConditionisdefined forR<3.0.2 and used byassertWarningthere.
Changes in version 1.1-1 (2013-12-28, svn r2933)
New Features
image(.., xlim, ylim): nicer defaults for the axislimits, andylimis sorted decreasingly; not strictlyback-compatible but should never harm.rankMatrix(*, method="qr")now usingtolT2graph()andgraph2T()export oldfunctionality explicitly. Tweaks in conversions betweengraphandsparseMatrixobjects. Notably,as(<graph>, <Matrix>)now more often returns a (0/1pattern) n..Matrix.sparseMatrix(): newuse.last.ijargument.
Bug Fixes
KhatriRao(): fix rownames (X <-> Y)qr.coef(),qr.fitted, andqr.residnowalso work withsparse RHSy.sparse matrix “sub assignments”, e.g.,
M[ii] <- v, speedup and fixes.bug fixes also in
M[negative indices] <- valueand<sparseMatrix>[cbind(i,j)].
Changes in version 1.1-0 (2013-10-21, svn r2930)
Dependencies
methods,stats,utils, andlatticeare moved from
DependstoImports.
SuiteSparse
The internal SuiteSparse library sources are updated to thelatest version. Use new function
.SuiteSparse_versiontoget the version in use.
C-Level API
‘inst/include/cholmod.h’ is updated to reflect changesin SuiteSparse. Notably, there were changes in the layout of thevarious
cholmod_*_struct.
New Features
fac2sparseandfac2Sparsenow exported, with anewgiveCsparseoption.
Bug Fixes
fixed long lasting undetected
solve(<dsCMatrix>, *)bug.Our
all.equal()methods no longer sometimes returnc("TRUE", "....difference..").rankMatrix(<matrix>): fix the internalx.densedefinition.
Changes in version 1.0-14 (2013-09-12, svn r2907)
Bug Fixes
Revert some wrong changes to
solve(<sparse>, *)from1.0-13 (“stop gap fix” forR 3.0.2).
Changes in version 1.0-13 (2013-09-10, svn r2904)
Classes
New nonvirtual class
indMatrixrepresenting row indexmatrices, i.e., matrices whose rows are standard unit vectors. ItextendssparseMatrixand is extended bypMatrix, theclass of permutation matrices.
Generic Functions
New generic functions
isTriangularandisDiagonalfor testing if the argument is (upper or lower)triangular or diagonal. These were defined previously but neverexported or documented.
New Features
Many methods for
pMatrixare generalized to supportindMatrix. All (initial) functionality was contributed byFabian Scheibl, Univ. Munich.New (efficient)
KhatriRao()function by MichaelCysouwrankMatrix(M, method="qr")no longer needssvalwhich makes it considerably more useful for largesparseM.Start providing
anyNAmethods forR\ge3.1.0.solve(<sparse> a, <sparse> b): ifaissymmetric, now computesparse result.nearPD()gets new optionconv.norm.type = "I".determinant(<dpoMatrix>)now useschol(), andhence also an existing (‘cached’) Cholesky factor.3 new
C -> Rutilities (including hiddenRfunction.set.factors()for caching also fromR, notjust in C).
Bug Fixes
M[] <- vfor unitriangularMnow correct.lu(.)no longer sometimes returns unsorted columns.
Changes in version 1.0-12 (2013-03-26, svn r2872)
New Features
.
Bug Fixes
.
Changes in version 1.0-11 (2013-02-02)
New Features
.
Bug Fixes
as(<csr>, "dgCMatrix")(from packageSparseM) now works again..
Changes in version 1.0-10 (2012-10-22)
New Features
.sparseDiagonal(): newunitriargument, andmore flexibility;new
solve(<dsCMatrix>, <missing>)via efficient Ccode.
Bug Fixes
.
Changes in version 1.0-9 (2012-09-05)
New Features
new
sparseVector()constructor function.is.finite()is.infinite()now work for ourmatrices andsparseVectorobjects.diag(.) <- Vnow preserves symmetricity,triangularity and even uni-triangularity sometimes.
Bug Fixes
Quite a few fixes for
Ops(arithmetic, logic, etc)group methods.Ditto for
diagonalMatrixmethods.
Changes in version 1.0-6 (2012-03-16)
New Features
.
Bug Fixes
.
Changes in version 1.0-5 (2012-03-15)
New Features
.
Bug Fixes
.
Changes in version 1.0-4 (2012-02-21)
New Features
.
Bug Fixes
.
Changes in version 1.0-3 (2012-01-13)
New Features
.
Bug Fixes
.
Changes in version 1.0-2 (2011-11-19)
New Features
.
Bug Fixes
.
Changes in version 1.0-1 (2011-10-18)
New Features
.
Bug Fixes
.
Changes in version 1.0-0 (2011-10-04)
New Features
.
Bug Fixes
.
Changes in version 0.9996875-3 (2011-08-13)
New Features
.
Bug Fixes
.
Changes in version 0.9996875-2 (2011-08-09)
New Features
.
Bug Fixes
.
Changes in version 0.9996875-1 (2011-08-08)
New Features
.
Bug Fixes
.
Changes in version 0.999375-50 (2011-04-08)
New Features
.
Bug Fixes
.
Changes in version 0.95-1 (2005-02-18, svn r561)
Authorship
During Douglas Bates' sabbatical in Zurich, Martin Maechlerbecomes co-author ofMatrix.
New Features
Beginning of class reorganization with a more systematicnaming scheme.
Bug Fixes
More (correct) coercions
as(<from>, <to>).
Changes in version 0.9-1 (2005-01-24, svn r451)
New Features
lme4 / lmer specificR code moved out tolme4package.
Bug Fixes
.
Changes in version 0.8-2 (2004-04-05, svn r51)
Description
Matrix version 0.8-2 is a full refactor. Classes,generic functions, and methods are newly implemented in S4.S3 machinery is removed. The remaining items in this sectiondescribe the state of things in version 0.8-2 rather than changessince version 0.3-26.
Matrix
\ge0.8-2 depends onR\ge1.9.0.Depends: methodsis added to ‘DESCRIPTION’.Douglas Bates becomes the sole author ofMatrix.
The package is retitled “Classes and Methods forNumerical Linear Algebra using LAPACK, LDL, TAUCS, METIS, andUMFPACK”.
The package sources are now maintained in a Subversionrepository.
Changes in version 0.3-26 (2003-11-03)
Bug Fixes
The default expressions of formal arguments
transposeandleftof generic functionfacmulare changed fromFandTtoFALSEandTRUE, as only thelatter are reserved words.
Changes in version 0.3-25 (2003-10-30)
Deprecated and Defunct
S3 generic function
determinantis removed as it wasported toR\ge1.8.0.
Significant User-Visible Changes
A namespace forMatrix is defined using directives in‘NAMESPACE’.
S3 generic functions
eigen,expand,facmul,lu,norm,rcond,schur,andunpackare exported.S3 methods are registered and not exported, hence theycontinue to be available but only through calls to exported S3generic functions.
Functions
Matrix,SVD,as.Matrix,diagDet, andhilbertare exported.Functions
Matrix.class,*.test, andis.*are exported but intended only for internal use.Functions
asObjectandprependClassare notexported.Load hook
.First.libis removed and replaced by auseDynLibdirective in ‘NAMESPACE’.
Changes in version 0.3-24 (2003-04-20)
Significant User-Visible Changes
S3 generic function
detis renameddeterminant.
Methods
determinant.Matrix(formerlydet.Matrix)computes theLUfactorization of its argument instead of theQRfactorization.
Changes in version 0.3-23 (2003-03-30)
Description
Matrix
\ge0.3-23 depends onR\ge1.7.0.
Installation
‘configure’, ‘configure.in’, ‘configure.win’,‘cleanup’, ‘src/Makevars.in’, and‘src/Makevars.win’ are removed and replaced by a simple‘src/Makevars’ arranging forMatrix to useR's
LAPACK_LIBSandBLAS_LIBS. The simplification ismade possible byR version 1.7-0, which is configured bydefault to build, link against, and install a shared LAPACK.
Changes in version 0.3-22 (2003-02-03)
Bug Fixes
Empty directory ‘data’ is removed.
Changes in version 0.3-21 (2002-10-25)
Description
The package is retitled “Classes and Methods forNumerical Linear Algebra using LAPACK”.
Installation
‘configure.win’ and ‘src/Makevars.win’ are addedto support installation under Windows, thanks to Brian Ripley.
More
#undefin the C++ sources to supportinstallation under Windows, thanks to Brian Ripley.
Changes in version 0.3-20 (2002-10-08)
Installation
‘configure.ac’ sets
CFLAGSbefore expandingAC_PROG_CCand setsFLIBSbefore expandingACX_BLASandACX_LAPACK.Autoconf macro
OCTAVE_BLAS_LIBS, which is no longerused, is removed from ‘aclocal.m4’.
Bug Fixes
Unwanted Autoconf output is removed from ‘aclocal.m4’.
Changes in version 0.3-19 (2002-07-22)
Bug Fixes
PACKAGE = "Matrix"is passed to.Calltorestrict name lookup toMatrix.The C++ sources use qualified name lookup (as in
std::<name>) in more places.The C++ sources get pointers to matrix datawithout taking the address of the first element, which is wrong fora matrix of length 0.
Changes in version 0.3-18 (2002-05-03)
Compatibility
*_ELTmacros are no longer defined forR<1.2.0 asMatrix depends onR\ge1.5.0.
Changes in version 0.3-17 (2002-04-30)
Description
Matrix
\ge0.3-17 depends onR\ge1.5.0.
Installation
‘configure.in’ is replaced by ‘configure.ac’contributed by Kurt Hornik. ‘configure.ac’ makes use of
R CMD config, a utility added inR version 1.5-0.Autoconf macros
ACX_BLASandACX_LAPACK,written by Steven G. Johnson, are added to ‘aclocal.m4’ andexpanded in ‘configure.ac’.The configured value of
LAPACK_LIBSis prepended toPKG_LIBSin ‘src/Makevars.in’.
Changes in version 0.3-16 (2001-12-10)
Documentation
A preliminary ‘ChangeLog’.
Compatibility
Rd files are adapted to use
\method{}{}markupintroduced inR version 1.2.2.One usage of
.Alias, deprecated inR version1.4.1, is removed.
Bug Fixes
S3 methods gain formal argument
...where needed tomatch the generic function.The name of a class member function in ‘src/tgmd.h’ waswas spuriously qualified.
Changes in version 0.3-15 (2001-05-15)
Installation
The configured value of
BLAS_LIBSis prepended toPKG_LIBSin ‘src/Makevars.in’.
Changes in version 0.3-13 (2001-05-10)
Installation
The C++ sources undefine macros
lengthandappendin many places to allow for class member functionswith those names.
Changes in version 0.3-10 (2001-05-04)
Bug Fixes
The C++ sources use qualified name lookup (as in
std::<name>) in more places.
Changes in version 0.3-9 (2001-03-09)
Bug Fixes
The C++ sources no longer write to
stderrand (in most places)stdout, no longer use theassertmacro, and no longer callexit.
Changes in version 0.3-8 (2001-01-10)
Description
‘DESCRIPTION’ gets a
Maintainerfield andDouglas Bates is named there.
Bug Fixes
Removes around 100 non-source files wrongly bundled inMatrix version 0.3-7.
Changes in version 0.3-7 (2000-12-03)
Installation
FLIBSis appended toPKG_LIBSin‘src/Makevars.in’.
Documentation
A basic ‘README’.
Changes in version 0.3-6 (2000-10-30)
Description
Matrix
\ge0.3-6 depends onR\ge1.1.1.
Installation
‘configure’ makes use of
HAVE_F77_UNDERSCOREin‘Rconfig.h’.PKG_LIBSandPKG_LDFLAGSto the configuredvalues ofLIBSandLDFLAGSin ‘src/Makevars.in’.
Changes in version 0.3-5 (2000-08-20)
Deprecated and Defunct
eigen.Matrixargumentschur, which was unused,is removed.
Methods
An S3 method
schur.Matrixinterfacing LAPACK routinedgeesx. It returnslist(values, schur, vectors).For arguments not inheriting from
MatrixsubclassHermitian,eigen.Matrixis now an interface toLAPACK routinedgeevx, and its optional argumentsbalanceandrcond, which were unused, can now beused to request balancing and the reciprocal condition numbers ofthe eigenvalues and right eigenvectors. The return value is nowlist(values, vectors, rcond)withvectors = list(left, right)andrcond = list(values, vectors).
Changes in version 0.3-3 (2000-08-11)
Installation
‘configure’ skips the check for BLAS in the SunPerformance Library if the C compiler is
gcc.
Compatibility
STRING_ELT,SET_STRING_ELT,VECTOR_ELT,andSET_VECTOR_ELTare used in place ofSTRINGandVECTOR.*_ELTmacros are defined forR<1.2.0 to not break compatibility.
Significant User-Visible Changes
SVD(x, nu = 0, nv)$uandSVD(x, nu, nv = 0)$vtareNULLrather than empty matrices.
Methods
An S3 method
lu.Matrixinterfacing LAPACK routinedgetrf. It returnslist(l, u, permutation), withattributenorms = list(one, infinity)containing the oneand infinity norms. An optional argument is provided to disablecomputation ofoneandinfinity.
Bug Fixes
SVD(x, nu, nv)allocated for the right singularvalues a matrix with dimensionsc(ncol(x), nv)instead ofc(nv, ncol(x)). Buffer overflow could occur in LAPACKroutinedgesvdifnv < ncol(x).
Changes in version 0.3-1 (2000-07-24)
Generic Functions
S3 generic function
eigen.
Methods
An S3 method
eigen.Matrixinterfacing LAPACK routinesdgeevanddsyev, the latter only for argumentsinheriting fromMatrixsubclassHermitian. Itreturnslist(values, vectors), wherevectorsislist(left, right)for non-Hermitianarguments and anumeric matrix forHermitianarguments. An optionalargument is provided to disable computation ofvectors.S3 methods
det.Matrix,det.UpperTriangular,det.UnitUpperTriangular,det.LowerTriangular, anddet.UnitLowerTriangularcomputing the modulus of thedeterminant or its logarithm. These returnlist(modulus, sign). Componentmodulushas alogical attributelogarithmindicating if the determinantissign * exp(modulus)orsign * modulus.det.Matrixcomputes theQRfactorization of itsargument using LAPACK routinedgeqrf.
Bug Fixes
Matrix.class(x)could be incomplete or contain badelements for orthogonalx.
New Features
A function
as.Matrixfor coercing an object toclassMatrix, parallel toas.matrix. The returnvalue inherits from subclasses ofMatrixif tests forstructure are satisfied.Functions
asObjectandprependClassforsetting and prepending to theclassattribute of theargument.A function
diagDetfor computing the determinant of atriangular matrix given the diagonal entries.
Changes in version 0.2-4 (2000-07-18)
Installation
A ‘configure’ script detecting options for linking BLASand LAPACK. It is generated from ‘configure.in’ which makesuse of an Autoconf macro
OCTAVE_BLAS_LIBSdefined in‘aclocal.m4’.‘src/Makevars’ is now generated from‘src/Makevars.in’.
A ‘cleanup’ script removing generated files.
Documentation
A Texinfo manual ‘R-Matrix.texi’ containingimplementation details and describing how LAPACK++ was modifiedforMatrix.
Methods
An S3 method
rcond.Matrixinterfacing LAPACK routinesd*con.
Bug Fixes
Exceptions thrown by LAPACK++ are caught and handled asRerrors.
UpperTriangular.testandLowerTriangular.testreturned a maximum rather than a maximum modulus for realarguments.
Changes in version 0.2-1 (2000-07-15)
Description
Matrix version 0.2-1 is the first one to bedistributed by CRAN.
The package is titled “A Matrix Library forR”.
Douglas Bates is the maintainer and principal author.Saikat DebRoy is a co-author.
Matrix
\ge0.2-1 depends onR\ge1.1.0.
Installation
A modified LAPACK++ (Linear Algebra PACKage in C++, version1.1a) is compiled alongside theMatrix sources. LAPACK++ isa C++ interface to LAPACK originally developed byRoldan Pozo.
Classes
S3 class
Matrixwith subclassesHermitian,UpperTriangular(recursively,UnitUpperTriangular),andLowerTriangular(recursively,UnitLowerTriangular). Objects are traditional numericmatrices with aclassattribute indicating theirstructural properties. Objects are interfaced in C++using the parallel class hierarchy defined by LAPACK++.
Generic Functions
S3 generic functions
det,expand,facmul,lu,norm,rcond,schur,andunpack.
Methods
An S3 method
norm.Matrixinterfacing LAPACK routinesdlan*.An S3 method
solve.Matrixinterfacing LAPACK routinesd*trfandd*trs.An S3 method
as.matrix.Matrixjust dropping the classattribute.An S3 method
print.Matrixjust printing theas.matrixresult.
New Features
A function
Matrixconstructing objects of classMatrixfrom numeric vectors and matrices, parallel tobase functionmatrix.A function
Matrix.classreturning a character vectorcontaining the subclasses ofMatrixthat would be valid forthe argument.Functions
Hermitian.test,UpperTriangular.test,LowerTriangular.test,Orthogonal.test, andOrthonormal.testreturning amaximum modulus distance useful for testing the respectiveproperty.Functions
is.Hermitian,is.UpperTriangular,is.LowerTriangular, andis.Orthonormaltesting ifthe*.testvalue does not exceed a tolerance.Function
SVDinterfacing LAPACK routinedgesvd.SVD(x, nu, nv)returnslist(d, u, vt)containing the singular values (sortednon-increasingly), firstnuleft singular vectors (storedcolumn-wise), and firstnvright singular vectors (storedrow-wise).Function
hilbertconstructing then-by-nHilbert matrix.