When the attribute V is read, a copy of V is
returned, as a new dense matrix.
(This implies, for example, that an indexed assignment
"A.V[I] = B" does not work, or at least
cannot be used to modify A. Instead the attribute V
will be read and returned as a new matrix; then the elements of this
new matrix are modified.)
V
. A read-only attribute.
V
. A read-only attribute.
) |
A.T
instead of A.trans()
.
) |
A.H
instead of A.ctrans()
.
In the following example we take the elementwise square root of
the matrix
>>> from cvxopt.base import sqrt >>> A = spmatrix([2,1,2,2,1,3,4], [1,2,0,2,3,0,2], [0,0,1,1,2,3,3]) >>> B = spmatrix(sqrt(A.V), A.I, A.J) >>> print B SIZE: (4,4) (1, 0) 1.4142e+00 (2, 0) 1.0000e+00 (0, 1) 1.4142e+00 (2, 1) 1.4142e+00 (3, 2) 1.0000e+00 (0, 3) 1.7321e+00 (2, 3) 2.0000e+00
The next example below illustrates assignments to V.
>>> from cvxopt.base import spmatrix, matrix >>> A = spmatrix(range(5), [0,1,1,2,2], [0,0,1,1,2]) >>> print A SIZE: (3,3) (0, 0) 0.0000e+00 (1, 0) 1.0000e+00 (1, 1) 2.0000e+00 (2, 1) 3.0000e+00 (2, 2) 4.0000e+00 >>> B = spmatrix(A.V, A.J, A.I, (4,4)) # transpose and add a zero row and column >>> print B SIZE: (4,4) (0, 0) 0.0000e+00 (0, 1) 1.0000e+00 (1, 1) 2.0000e+00 (1, 2) 3.0000e+00 (2, 2) 4.0000e+00 >>> print matrix(B) 0.0000e+00 1.0000e+00 0.0000e+00 0.0000e+00 0.0000e+00 2.0000e+00 3.0000e+00 0.0000e+00 0.0000e+00 0.0000e+00 4.0000e+00 0.0000e+00 0.0000e+00 0.0000e+00 0.0000e+00 0.0000e+00 >>> B.V[:] = 1., 7., 8., 6., 4. # assign new values to nonzero entries >>> print B SIZE: (4,4) (0, 0) 1.0000e+00 (0, 1) 7.0000e+00 (1, 1) 8.0000e+00 (1, 2) 6.0000e+00 (2, 2) 4.0000e+00 >>> B.V += 1.0 # add 1 to the nonzero entries >>> print B SIZE: (4,4) (0, 0) 2.0000e+00 (0, 1) 8.0000e+00 (1, 1) 9.0000e+00 (1, 2) 7.0000e+00 (2, 2) 5.0000e+00
The V, I and J attributes can be used for reading sparse matrices from or writing them to binary files. Suppose we want to write the matrix A defined above to a binary file.
>>> f = open('test.bin','w') >>> A.V.tofile(f) >>> A.I.tofile(f) >>> A.J.tofile(f) >>> f.close()
>>> f = open('test.bin','r') >>> V = matrix(0.0, (5,1)); V.fromfile(f) >>> I = matrix(0, (5,1)); I.fromfile(f) >>> J = matrix(0, (5,1)); J.fromfile(f) >>> B = spmatrix(V, I, J) >>> print B SIZE: (3,3) (0, 0) 0.0000e+00 (1, 0) 1.0000e+00 (1, 1) 2.0000e+00 (2, 1) 3.0000e+00 (2, 2) 4.0000e+00
Note that the pickle module provides a convenient alternative to this method.