[Numpy-discussion] Matlab -> NumPy translation and indexing

Christopher Barker Chris.Barker@noaa....
Mon Mar 5 12:04:03 CST 2007

```David Koch wrote:
> - Is it "pythonic" to initialize vectors to 2 dimensions so that
> vec.shape == (len(vec), 1) instead of vec.shape == (len(vec),)?

It depends what it means -- and this is not a question of Pythonic --
maybe Numpythonic?

Numpy is an n-d array package -- NOT a matrix package (if you really
want matrices, see the numpy matrix package).

thus, a Vector can be represented as a (n,) shaped array
a Matrix can be represented by a (n,m) shaped array
etc...

If what you want is a matrix that happens to have one column, you want a
(n,1) array, if you want one row, you want a (1,n) array. In linear
algebra terms, these are row and column vectors. In other math, a vector
is (n,) in shape.

Other than linear algebra, a reason to use 2-d "vectors" is for array

>>> import numpy as N
>>> x = N.arange(10).reshape(1,-1) # a "row" vector
>>> y = N.arange(5).reshape(-1,1) # a "column" vector
>>> x.shape
(1, 10)
>>> y.shape
(5, 1)
>>> z = x * y
>>> z
array([[ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
[ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18],
[ 0,  3,  6,  9, 12, 15, 18, 21, 24, 27],
[ 0,  4,  8, 12, 16, 20, 24, 28, 32, 36]])
>>>

## note that you didn't' really need to reshape x, as a (n,) array is
interpreted as a row vector for broadcasting purposes, but I like to do
it for clarities sake.

In MATLAB, there is no such thing as a vector, so you only have the last
two options -- not the first.

-Chris

--
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker@noaa.gov
```