[Numpy-discussion] matrix default to column vector?

Tom K. tpk@kraussfamily....
Sun May 24 07:32:22 CDT 2009

```
Jason Rennie-2 wrote:
>
> By default, it looks like a 1-dim ndarray gets converted to a row vector
> by
> the matrix constructor.  This seems to lead to some odd behavior such as
> a[1] yielding the 2nd element as an ndarray and throwing an IndexError as
> a
> matrix.  Is it possible to set a flag to make the default be a column
> vector?
>

I'm not aware of any option that changes the construction behavior of
"matrix".  I honestly don't work with matrices very often - I just stick
with arrays.

".T" will do what you want of course:
x = matrix(range(10)).T

As for odd behavior, can you say what in particular is odd about it?  For
the example that you mention, let's consider it in greater depth:
x=np.array(range(5))
x[1] --> 1
x=np.matrix(range(5))
x[1] --> raises IndexError "index out of bounds"

So it appears that with *matrices* as opposed to arrays, indexing with just
1 index has an implicit ":" as a 2nd index.  This is distinctly different
than the behavior for *arrays* where indexing with just 1 index returns a
new nd-array with one fewer dimensions.  I think it boils down to this: a
matrix always has 2 dimensions, so indexing into it (whether with one or
both indices specified) returns another 2D matrix; with arrays which are ND,
indexing with just a single (integer) index returns an N-1 D array.  When I
look at it like this, np's indexing error is just exactly what I would
expect (given that it creates a row vector).

If you are going to use matrix in numpy, you must realize that x[n] for
matrix x is equivalent to x[n,:].

Maybe my reluctance to work with matrices stems from this kind of
inconsistency.  It seems like your code has to be all matrix, or all array -
and if you mix them, you need to be very careful about which is which.  It
is just easier for me to work only with array, and when needing to do matrix
stuff just call "dot".  Come to think of it, why doesn't 1/x for matrix x
invert the matrix like in MATLAB?  How about x\1? (Yeah, I know I'm pushing
it now :-)

As for adding an option that changes to behavior of matrix creation to be
"transposed" I don't like it since the code will now do different things
depending on whether the option is set.  So, to write "safe" code you would
have to check the option each time.
--
View this message in context: http://www.nabble.com/matrix-default-to-column-vector--tp23652920p23693116.html
Sent from the Numpy-discussion mailing list archive at Nabble.com.

```