[Numpy-discussion] strange behavior of ravel() and flatnonzero() on matrix
Robert Kern
robert.kern@gmail....
Wed Nov 3 18:30:49 CDT 2010
On Wed, Nov 3, 2010 at 18:04, braingateway <braingateway@gmail.com> wrote:
>>>> aa=matrix([[-1, 2, 0],[0, 0, 3]])
>>>> aa
> matrix([[-1, 2, 0],
> [ 0, 0, 3]])
>>>> aa.nonzero()
> (matrix([[0, 0, 1]], dtype=int64), matrix([[0, 1, 2]], dtype=int64))
> *********OK*********
>>>> npy.nonzero(aa.flat)
> (array([0, 1, 5], dtype=int64),)
> *********OK*********
>>>> flatnonzero(aa)
> matrix([[0, 0, 0]], dtype=int64)
> *******This is Wrong**********
> If I convert aa to an ndarray, it is OK then
> aaa=asarray(aa)
>>>> flatnonzero(aaa)
> array([0, 1, 5], dtype=int64)
>
> Then I figure it out that it might be induced by the behavior of ravel()
>>>> aaa.shape
> (2L, 3L)
>>>> aaa.ravel().shape
> (6L,)
>>>> aa.ravel()
> matrix([[-1, 2, 0, 0, 0, 3]])
>>>> _.shape
> (1L, 6L)
> Why not make ravel() behaviors consistent under both ndarray and matrix
> contexts?
> Or make different flatnonzero() for the matrix context?
> m.ravel().nonzero()[1]# for matrix
> a.ravel().nonzero()[0]# for ndarray
Most of the ndarray methods will make sure that they return the same
subclass of ndarray that the original object is. So
type(some_matrix.ravel()) is also matrix. Since matrix objects are
always 2D, you get the above behavior. One could probably overwrite
those methods to return ndarrays of the proper shape instead.
If you are doing such shape-manipulating operations, though, I highly
recommend just using ndarray objects and never using matrix objects.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
-- Umberto Eco
More information about the NumPy-Discussion
mailing list