[Numpy-discussion] mixing arrays and matrices: squeeze yes, flattened no?

Sven Schreiber svetosch at gmx.net
Tue Feb 21 05:43:03 CST 2006


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

First conclusion: broadcasting is nice and everything, but here I
somehow think that it shouldn't be like this. I like numpy, but this is
frustrating.

Next, I try to workaround by b.squeeze(). That seems to work, but why is
b.squeeze().shape == (1, 112) instead of (112,)?

Then I thought maybe b.flattened() does the job, but then I get an error
(matrix has no attr flattened). Again, I'm baffled.

Could someone please explain? I already own the numpy-book, otherwise I
wouldn't even have thought of using those methods, but here it hasn't
enlightened me.

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" ?

Thanks for any insights,
Sven





More information about the Numpy-discussion mailing list