Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add to numpy array entries of different size in a for loop (similar to Matlab's cell arrays)?

I'm trying to implement an analouge to Matlab's cell array in python \ numpy. The Matlab code would go like that :

for n=1:10
    C{n} = rand(1,n);
end

Note that each cell element has a different length. Now in numpy:

for n in np.arange(10):
    C[n] = np.random.rand(1,n)

and I get an error, what can I do to implement this?

like image 469
bla Avatar asked Oct 31 '25 10:10

bla


1 Answers

In most simple cases, you could just use a standard Python list. They are pretty similar to Matlab cell-arrays, you can use them to store anything:

C = []
for n in np.arange(10):
    C.append(np.random.rand(1,n))

This would be a good option if the list is not too long and if it only has a single dimension (so just a vector). Note that in Python, you typically do not pre-allocate a list of the final size, but simply append to an empty list. Python lists are optimized for appending to the end, they already do some sort of pre-allocation under the hood.

If you are translating Matlab code with cell-arrays of multiple dimensions, or ones that are very large, you could use numpy arrays with dtype=object:

m, n = 3, 6
C = np.empty((m, n), dtype=object)
for i in xrange(m):
    for j in xrange(n):
        C[i, j] = np.random.rand(i, j)
like image 192
Bas Swinckels Avatar answered Nov 02 '25 01:11

Bas Swinckels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!