[Numpy-discussion] Indexing bug
Aronne Merrelli
aronne.merrelli at gmail.com
Fri Apr 5 12:11:03 EDT 2013
On Sun, Mar 31, 2013 at 12:14 AM, Ivan Oseledets
<ivan.oseledets at gmail.com>wrote:
<snip>
Oh! So it is not a bug, it is a feature, which is completely
> incompatible with other array based languages (MATLAB and Fortran). To
> me, I can not find a single explanation why it is so in numpy.
> Taking submatrices from a matrix is a common operation and the syntax
> above is very natural to take submatrices, not a weird diagonal stuff.
> i.e.,
>
> c = np.random.randn(100,100)
> d = c[[0,3],[2,3]]
>
> should NOT produce two numbers! (and you can not do it using slices!)
>
> In MATLAB and Fortran
> c(indi,indj)
> will produce a 2 x 2 matrix.
> How it can be done in numpy (and why the complications?)
>
> So, please consider this message as a feature request.
>
>
There is already a function, ix, in the index_tricks that does this (I
think it is essentially implementing the broadcasting trick that Nathaniel
mentions. For me the index trick is easier, as I often forget the
broadcasting details). Example:
In [14]: c = np.random.randn(100,100)
In [15]: c[[0,3],[2,3]]
Out[15]: array([ 0.99141998, -0.88928917])
In [16]: c[np.ix_([0,3],[2,3])]
Out[16]:
array([[ 0.99141998, -1.98406295],
[ 0.0729076 , -0.88928917]])
So for me, I think this is superior to MATLAB, as I have often had the case
of wanting the result from the second option. In MATLAB you would need to
extract the 2x2 matrix, and then take its diagonal. This can be wasteful
when the index arrays become large.
Cheers,
Aronne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20130405/0d5ea0f7/attachment.html>
More information about the NumPy-Discussion
mailing list