2

I'm having trouble resizing a matrix - the set_shape function seems to have no effect:

>>> M
<14x3562 sparse matrix of type '<type 'numpy.float32'>'
   with 6136 stored elements in LInked List format>
>>> new_shape = (15,3562)
>>> M.set_shape(new_shape)
>>> M
<14x3562 sparse matrix of type '<type 'numpy.float32'>'
   with 6136 stored elements in LInked List format>

Anyone else come across this?

I also tried doing this by hand, i.e.

>>> M._shape = new_shape
>>> M.data = np.concatenate(M.data, np.empty((0,0), dtype=np.float32))

but that throws up an error:

*** TypeError: only length-1 arrays can be converted to Python scalars

or

>>> M.data = np.concatenate(M.data, [])
*** TypeError: an integer is required

For info:

  • Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
  • scipy 0.11.0.dev-03f9e4a
sodd
  • 12,482
  • 3
  • 54
  • 62
tdc
  • 8,219
  • 11
  • 41
  • 63

1 Answers1

5

If you just want to add a row of zeros at the end:

>>> M = sp.lil_matrix((14, 3562))
>>> sp.vstack([M, sp.lil_matrix((1, 3562))])
<15x3562 sparse matrix of type '<type 'numpy.float64'>'
        with 0 stored elements in COOrdinate format>
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • Weirdly that gives me an error: `row = sparse.lil_matrix((1,3562))` followed by `sparse.vstack(M, row)` gives `*** NotImplementedError: adding a scalar to a CSC or CSR matrix is not supported` – tdc Mar 08 '12 at 17:24
  • and before you ask M is definitely a lil matrix! – tdc Mar 08 '12 at 17:29
  • 3
    @tdc: that's `sparse.vstack([M, row])`. – Fred Foo Mar 08 '12 at 17:40
  • genius, thanks. I've been shaving yaks all afternooon with this one!! – tdc Mar 08 '12 at 18:01