Numpy:作为Matlab的作业和索引 [英] Numpy: Assignment and Indexing as Matlab

查看:134
本文介绍了Numpy:作为Matlab的作业和索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时仅为一个索引分配数组很有用。在Matlab中,这很简单:

Sometimes is useful to assign arrays with one index only. In Matlab this is straightforward:

M = zeros(4);
M(1:5:end) = 1
M =

   1   0   0   0
   0   1   0   0
   0   0   1   0
   0   0   0   1

Numpy有没有办法做到这一点?首先,我想要展平数组,但该操作不会保留引用,因为它会复制。我尝试使用ix_但我无法用相对简单的语法来完成它。

Is there a way to do this in Numpy? First I thought to flatten the array, but that operation doesn't preserve the reference, as it makes a copy. I tried with ix_ but I couldn't manage to do it with a relatively simple syntax.

推荐答案

你可以试试 numpy.ndarray.flat ,它表示可用于读取和写入数组的迭代器。

You could try numpy.ndarray.flat, which represents an iterator that you can use for reading and writing into the array.

>>> M = zeros((4,4))
>>> M.flat[::5] = 1
>>> print(M)
array([[ 1.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  1.]])

请注意,在numpy中,切片语法是[start:stop_exclusive:step],而不是Matlab的(start:step:stop_inclusive)。

Note that in numpy the slicing syntax is [start:stop_exclusive:step], as opposed to Matlab's (start:step:stop_inclusive).

根据sebergs注释,指出Matlab将矩阵存储在专业列中可能很重要,而numpy数组默认为行专业。

Based on sebergs comment it might be important to point out that Matlab stores matrices in column major, while numpy arrays are row major by default.

>>> M = zeros((4,4))
>>> M.flat[:4] = 1
>>> print(M)
array([[ 1.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])

要在展平数组上获得类似Matlab的索引,您需要展平转置数组:

To get Matlab-like indexing on the flattened array you will need to flatten the transposed array:

>>> M = zeros((4,4))
>>> M.T.flat[:4] = 1
>>> print(M)
array([[ 1.,  0.,  0.,  0.],
       [ 1.,  0.,  0.,  0.],
       [ 1.,  0.,  0.,  0.],
       [ 1.,  0.,  0.,  0.]])

这篇关于Numpy:作为Matlab的作业和索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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