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]]  
[ 0.00e+00  2.00e+00]  
[ 2.00e+00     0    ]  
[-1.00e+00 -2.00e+00]  
>>> B = spmatrix([0,2*1j,0,-2], [1,2,1,2], [0,0,1,1,])  
>>> print B[-2:,-2:]  
[ 0.00e+00-j0.00e+00  0.00e+00-j0.00e+00]  
[ 0.00e+00+j2.00e+00 -2.00e+00-j0.00e+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  
[ 1.00e+01  2.00e+00     0    ]  
[    0         0      1.00e+00]  
[-2.00e+01 -2.00e+00     0    ]  
>>> D = matrix(range(6), (3,2))  
>>> A[:,0] = D[:,0]  
>>> print A  
[ 0.00e+00  2.00e+00     0    ]  
[ 1.00e+00     0      1.00e+00]  
[ 2.00e+00 -2.00e+00     0    ]  
>>> A[:,0] = 1  
>>> print A  
[ 1.00e+00  2.00e+00     0    ]  
[ 1.00e+00     0      1.00e+00]  
[ 1.00e+00 -2.00e+00     0    ]  
>>> A[:,0] = 0  
>>> print A  
[ 0.00e+00  2.00e+00     0    ]  
[ 0.00e+00     0      1.00e+00]  
[ 0.00e+00 -2.00e+00     0    ]