python - Extract non-main diagonal from scipy sparse matrix? -


say have sparse matrix in scipy.sparse format. how can extract diagonal other than main diagonal? numpy array, can use numpy.diag. there scipy sparse equivalent?

for example:

from scipy import sparse = sparse.diags(ones(5),1) 

how vector of ones without converting numpy array?

when sparse array in dia format, data along diagonals recorded in offsets , data attributes:

import scipy.sparse sparse import numpy np  def make_sparse_array():     = np.arange(ncol*nrow).reshape(nrow, ncol)     row, col = zip(*np.ndindex(nrow, ncol))     val = a.ravel()      = sparse.coo_matrix(         (val, (row, col)), shape=(nrow, ncol), dtype='float')     = a.todia()     # = sparse.diags(np.ones(5), 1)     # = sparse.diags([np.ones(4),np.ones(3)*2,], [2,3])     print(a.toarray())     return  nrow, ncol = 10, 5 = make_sparse_array() diags = {offset:(diag[offset:nrow+offset] if 0<=offset<=ncol else                  diag if offset+nrow-ncol>=0 else                  diag[:offset+nrow-ncol])          offset, diag in zip(a.offsets, a.data)}   offset, diag in sorted(diags.iteritems()):     print('{o}: {d}'.format(o=offset, d=diag)) 

thus array

[[  0.   1.   2.   3.   4.]  [  5.   6.   7.   8.   9.]  [ 10.  11.  12.  13.  14.]  [ 15.  16.  17.  18.  19.]  [ 20.  21.  22.  23.  24.]  [ 25.  26.  27.  28.  29.]  [ 30.  31.  32.  33.  34.]  [ 35.  36.  37.  38.  39.]  [ 40.  41.  42.  43.  44.]  [ 45.  46.  47.  48.  49.]] 

the code above yields

-9: [ 45.] -8: [ 40.  46.] -7: [ 35.  41.  47.] -6: [ 30.  36.  42.  48.] -5: [ 25.  31.  37.  43.  49.] -4: [ 20.  26.  32.  38.  44.] -3: [ 15.  21.  27.  33.  39.] -2: [ 10.  16.  22.  28.  34.] -1: [  5.  11.  17.  23.  29.] 0: [  0.   6.  12.  18.  24.] 1: [  1.   7.  13.  19.] 2: [  2.   8.  14.] 3: [ 3.  9.] 4: [ 4.] 

the output above printing offset followed diagonal @ offset.

the code above should work sparse array. used populated sparse array make easier check output correct.


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -