|
From: Travis O. <oli...@ie...> - 2006-02-21 19:12:47
|
Sven Schreiber wrote: >Hi, sometimes I'm still struggling with peculiarities of numpy-arrays >vs. numpy-matrices; my latest story goes like this: > >I first slice out a column of a 2d-numpy-array (a = somearray[:,1]). I >can just manage to understand the resulting shape ( == (112,) ). > >Then I slice a column from a numpy-matrix b = somematrix[:,1] and get >the expected (112,1) shape. > >Then I do what I thought was the easiest thing in the world, I subtract >the two vectors: c = a - b >I was very surprised by the bug that showed up due to the fact that >c.shape == (112,112) !! > > As you know this isn't a bug, but very expected behavior. I don't see this changing any time soon. Arrays are different than matrices. Matrices are always 2-d arrays while arrays can have any number of dimensions. The default relationship between arrays and matrices is that 1-d arrays get converted to row-matrices (1,N). Regardless of which convention is chosen somebody will be bitten by that conversion if they think in terms of the other default. I don't see a way around that except to be careful when you mix arrays and matrices. >Next, I try to workaround by b.squeeze(). That seems to work, but why is >b.squeeze().shape == (1, 112) instead of (112,)? > > Again the same reason as before. A matrix is returned from b.squeeze() and there are no 1-d matrices. Thus, you get a row-vector. Use .T if you want a column vector. >Then I thought maybe b.flattened() does the job, but then I get an error >(matrix has no attr flattened). Again, I'm baffled. > > The correct spelling is b.flatten() And again you are going to get a (1,N) matrix out because of how 1d arrays are interpreted as matrices. In short, there is no way to get a 1-d matrix because that doesn't make sense. You can get a 1-d array using b.A.squeeze() >Second (preliminary) conclusion: I will paranoically use even more >asmatrix()-conversions in my code to avoid dealing with those >array-beasts ;-) and get column vectors I can trust... > > > >Is there a better general advice than to say: "numpy-matrices and >numpy-arrays are best kept in separated worlds" ? > > You can mix arrays and matrices just fine if you remember that 1d arrays are equivalent to row-vectors. -Travis |