Most of the operations defined for dense ’d’ and ’z’ matrices (section 2.3) are also defined for sparse matrices. In the following table, A is a sparse matrix, B is sparse or dense, and c is a scalar, defined as a Python number or a 1 by 1 dense matrix.
Unary plus/minus | +A, -A |
Addition | A+B, B+A, A+c, c+A |
Subtraction | A-B, B-A, A-c, c-A |
Matrix multiplication | A*B, B*A |
Scalar multiplication and division | c*A, A*c, A/c |
If B is a dense matrix, then the result of A+B, B+A, A-B, B-A is a dense matrix. The typecode of the result is ’d’ if A has typecode ’d’ and B has typecode ’i’ or ’d’, and it is ’z’ if A and/or B have typecode ’z’.
If B is a sparse matrix, then the result of A+B, B+A, A-B, B-A is a sparse matrix. The typecode of the result is ’d’ if A and B have typecode ’d’, and ’z’ otherwise.
If c in A+c, A-c, c+A, c-A is a number, then it is interpreted as a dense matrix with the same size as A, typecode given by the type of c, and all entries equal to c. If c is a 1 by 1 dense matrix and the size of A is not 1 by 1, then c is interpreted as a dense matrix of the same size as A, typecode given by the typecode of c, and all entries equal to c[0].
The result of a matrix-matrix product A*B or B*A is a dense matrix if B is dense, and sparse if B is sparse. The matrix-matrix product is not allowed if B is a dense ’i’ matrix.
If c is a number (Python integer float or complex), then the operations c*A and A*c define scalar multiplication and return a sparse matrix.
If c is a 1 by 1 dense matrix, then, if possible, the products c*A and A*c are interpreted as matrix-matrix products and a dense matrix is returned. If the product cannot be interpreted as a matrix-matrix product (either because the dimensions of A are incompatible or because c has typecode ’i’), then the product is interpreted as the scalar multiplication with c[0] and a sparse matrix is returned.
The division A/c is interpreted as scalar multiplication with 1.0/c if c is a number, or with 1.0/c[0] if c is a 1 by 1 dense matrix.
The following in-place operations are defined for a sparse matrix A if they do not change the dimensions or type of A.
In-place addition | A+=B, A+=c |
In-place subtraction | A-=B, A-=c |
In-place scalar multiplication and division | A*=c, A/=c |
For example, ”A += 1.0” is not allowed because the operation ”A = A + 1.0” results in a dense matrix, so it cannot be assigned to A without changing its type.
In-place matrix-matrix products are not allowed. (Except when c is a 1 by 1 dense matrix, in which case A*=c is interpreted as a scalar product A*=c[0].)
As for dense operations, the in-place sparse operations do not return a new matrix but modify the existing object A.