[SciPy-user] ragged arrays

John Hunter jdhunter at ace.bsd.uchicago.edu
Sun Jun 4 16:51:04 CDT 2006


>>>>> "David" == David Grant <david.grant at telus.net> writes:

    David> Simple question, in Matlab you can do ragged arrays using
    David> "cell arrays." Is the equivalent thing in
    David> scipy/numpy/python just a List of arrays? I made one here:

    David> In [55]:a Out[55]: [array([0, 0, 0, 0, 0]), array([0, 0, 0,
    David> 0, 0, 0]), array([0, 0, 0, 0]), array([1, 1, 1, 1])]

Oh man, that brings back a dreadful past -- cell arrays.  The built-in
python data structures are much richer.  You can use a list or a
dictionary to store them, or a class that derives from one of these or
a custom class.

One good solution is to derive a custom class from list with helper
methods to operate over the list of arrays.  Eg, if you needed to find
the max element over all of your ragged arrays, you could do something
like

class ragged(list):
    def max(self):
        return max([max(x) for x in self])

import numpy as n
n1 = n.rand(10)
n2 = n.rand(20)
n3 = n.rand(30)

r = ragged((n1, n2, n3))
print r.max()

n4 = n.rand(12)
r.append(n4)
print r.max()



JDH



More information about the SciPy-user mailing list