3

I initialize an empty sparse matrix using

S = scipy.sparse.lil_matrix((n,n),dtype=int)

As expected print S doesn't show anything, since nothing has been assigned. Yet if I test:

print S[0,0]==0

I receive true.

Is there a way to test if a value has been set before? E.g. along the lines of ifempty?

Markus
  • 1,215
  • 1
  • 12
  • 19
  • The point of a sparse matrix is that most of the values are *0*. There is no "unassigned" value. – Warren Weckesser Dec 13 '13 at 23:10
  • That is not quite true. If I assign a explicit 0 to a entry, i.e. `S[0,0]=0` and I call `print S`, I get the value returned: `(0, 0) 0`. So somehow it can be distinguished between unassigned and 0. – Markus Dec 13 '13 at 23:14
  • Sure, but you won't be able to tell from accessing S[0,0]. You'd have to dig into the underlying representation. So it will depend on the format of the sparse matrix (e.g. CSR, DOK, COO, etc). – Warren Weckesser Dec 13 '13 at 23:17

1 Answers1

1

You can check for stored values with

def get_items(s):
    s_coo = s.tocoo()
    return set(zip(s_coo.row, s_coo.col))

Demo:

>>> n = 100
>>> s = scipy.sparse.lil_matrix((n,n),dtype=int)
>>> s[10, 12] = 1
>>> (10, 12) in get_items(s)
True

Note that for other types of sparse matrices, 0 can be expicetely set:

>>> s = scipy.sparse.csr_matrix((n,n),dtype=int)
>>> s[12, 14] = 0
>>> (12, 14) in get_items(s)
True
alko
  • 46,136
  • 12
  • 94
  • 102
  • I don't recommend depending on the 'explicit zero' functionality across Scipy versions, particularly in lines like `s[12, 14] = 0`. To my knowledge it is not a tested API feature. – joeln Mar 05 '14 at 02:30