6.4 Indexing and Slicing

Sparse matrices can be indexed the same way as dense matrices (see section 2.4 ).

>>> from cvxopt.base import spmatrix
>>> A = spmatrix([0,2,-1,2,-2,1], [0,1,2,0,2,1], [0,0,0,1,1,2]) 
>>> print A[:,[0,1]]
SIZE: (3,2)
(0, 0)  0.0000e+00
(1, 0)  2.0000e+00
(2, 0) -1.0000e+00
(0, 1)  2.0000e+00
(2, 1) -2.0000e+00
>>> B = spmatrix([0,2*1j,0,-2], [1,2,1,2], [0,0,1,1,])
>>> print B[-2:,-2:]
SIZE: (2,2)
(0, 0)  0.0000e+00-j0.0000e+00
(1, 0)  2.0000e+00-j0.0000e+00
(0, 1)  0.0000e+00-j0.0000e+00
(1, 1)  0.0000e+00-j2.0000e+00

An indexed sparse matrix A[I] or A[I,J] can also be the target of an assignment. The righthand side of the assignment can be a scalar (a Python integer, float, or complex, or a 1 by 1 dense matrix), a sequence of numbers, or a sparse or dense matrix of compatible dimensions. If the righthand side is a scalar, it is treated as a dense matrix of the same size as the lefthand side and with all its entries equal to the scalar. If the righthand side is a sequence of numbers, they are treated as the elements of a dense matrix in column-major order.

We continue the example above.

>>> C = spmatrix([10,-20,30], [0,2,1], [0,0,1])
>>> A[:,0] = C[:,0]
>>> print A
SIZE: (3,3)
(0, 0)  1.0000e+01
(2, 0) -2.0000e+01
(0, 1)  2.0000e+00
(2, 1) -2.0000e+00
(1, 2)  1.0000e+00
>>> D = matrix(range(6), (3,2))
>>> A[:,0] = D[:,0]
>>> print A
SIZE: (3,3)
(0, 0)  0.0000e+00
(1, 0)  1.0000e+00
(2, 0)  2.0000e+00
(0, 1)  2.0000e+00
(2, 1) -2.0000e+00
(1, 2)  1.0000e+00
>>> A[:,0] = 1
>>> print A
SIZE: (3,3)
(0, 0)  1.0000e+00
(1, 0)  1.0000e+00
(2, 0)  1.0000e+00
(0, 1)  2.0000e+00
(2, 1) -2.0000e+00
(1, 2)  1.0000e+00
>>> A[:,0] = 0
>>> print A
TYPE: (3,3)
(0, 0)  0.0000e+00
(1, 0)  0.0000e+00
(2, 0)  0.0000e+00
(0, 1)  2.0000e+00
(2, 1) -2.0000e+00
(1, 2)  1.0000e+00