Search code examples
pythonreducesparse-matrix

reduce() hstack python


I am trying to use reduce() function to create a function hstack() which horizontally stacks multiple arrays. As a simple example, lets say

>>>>M=eye((4))
>>>>M
    array([[ 1.,  0.,  0.,  0.],
    [ 0.,  1.,  0.,  0.],
    [ 0.,  0.,  1.,  0.],
    [ 0.,  0.,  0.,  1.]])

>>>>hstack([M,M])
array([[ 1.,  0.,  0.,  0.,  1.,  0.,  0.,  0.],
   [ 0.,  1.,  0.,  0.,  0.,  1.,  0.,  0.],
   [ 0.,  0.,  1.,  0.,  0.,  0.,  1.,  0.],
   [ 0.,  0.,  0.,  1.,  0.,  0.,  0.,  1.]])

This works as I want. Now I define

>>>> hstackm = lambda *args: reduce(hstack, args)

And try to do the hstack() from the previous case

>>>>hstackm([M,M])  
[array([[ 1.,  0.,  0.,  0.],
   [ 0.,  1.,  0.,  0.],
   [ 0.,  0.,  1.,  0.],
   [ 0.,  0.,  0.,  1.]]),
 array([[ 1.,  0.,  0.,  0.],
   [ 0.,  1.,  0.,  0.],
   [ 0.,  0.,  1.,  0.],
   [ 0.,  0.,  0.,  1.]])]

Which is incorrect. How do I define hstackm() to obtain a proper output?

My final objective will be to create a hstackm() function to stack SPARSE matrices if it is possible. Something like,

hstackm = lambda *args: reduce(sparse.hstack, args).

The _*args_ would be csr or _lil_matrix_

thank you


Solution

  • In [16]: hstackm = lambda args: reduce(lambda x,y:hstack((x,y)), args)
    
    In [17]: hstackm([M,M])
    Out[17]: 
    array([[ 1.,  0.,  0.,  0.,  1.,  0.,  0.,  0.],
           [ 0.,  1.,  0.,  0.,  0.,  1.,  0.,  0.],
           [ 0.,  0.,  1.,  0.,  0.,  0.,  1.,  0.],
           [ 0.,  0.,  0.,  1.,  0.,  0.,  0.,  1.]])