如何在for循环中添加到不同大小的numpy数组条目(类似于Matlab的单元格数组)? [英] How to add to numpy array entries of different size in a for loop (similar to Matlab's cell arrays)?

查看:65
本文介绍了如何在for循环中添加到不同大小的numpy数组条目(类似于Matlab的单元格数组)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在python \ numpy中实现对Matlab的单元格数组的模拟.Matlab代码将像这样:

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

请注意,每个单元格元素的长度都不同.现在是numpy:

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?

推荐答案

在大多数简单情况下,您可以只使用标准的Python列表.它们与Matlab细胞阵列非常相似,您可以使用它们存储任何东西:

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))

如果列表不太长并且仅具有一个维度(因此只有一个向量),则这将是一个不错的选择.请注意,在Python中,通常不预先分配最终大小的列表,而只是追加到空列表中.Python列表经过优化,可以附加到末尾,它们已经在后台进行了一些预分配.

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.

如果您要翻译具有多个维度或非常大的元胞数组的Matlab代码,则可以将numpy数组与 dtype = object 一起使用:

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)

这篇关于如何在for循环中添加到不同大小的numpy数组条目(类似于Matlab的单元格数组)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆