# What is the best way to define a row vector in NumPy?

I'm relatively new to NumPy.

In Matlab, making a row vector was pretty simple.

x = [1, 2, 3]

In NumPy, I think the following "y" is actually not a row vector.

y = np.array([1, 2, 3])

since it is one dimensional. Additionally, the following "z" is a column vector not a row vector.

z= np.array([[1], [2], [3]])

In NumPy, to do the same thing, how I can do it? One way is doing the following:

x = np.array([[1], [2], [3]]).transpose()

But it looks somewhat absurd. Could anyone give some suggestions on this?

Thanks,

## Answers

If by "row vector" you mean a matrix (2d array) with 1 row, then you need

x = np.array([[1,2,3]])

or more easily

x1d = np.array([1,2,3]) x = x1d[None,:] #insert singleton dimension

Think of ndarrays as lists of lists (of list of lists of...). For a 2d array, each row is a list. Hence [[1,2,3]]. This also explains why you need to use [[1],[2],[3]] for a column.

But for almost any application a 1d numpy array is as good as a row vector. For columns, however, you do need to use something like x1d[:,None].

The difference between the three kinds of variables:

In [496]: x1d.shape Out[496]: (3,) In [497]: x1d[None,:].shape Out[497]: (1, 3) In [498]: x1d[:,None].shape Out[498]: (3, 1)

So often you don't have to use an explicit row vector but a 1d array will suffice. Most importantly, broadcasting of a 1d array works as with a 2d row vector:

In [501]: x1d+np.ones((3,3)) Out[501]: array([[ 2., 3., 4.], [ 2., 3., 4.], [ 2., 3., 4.]]) In [502]: x1d[None,:]+np.ones((3,3)) Out[502]: array([[ 2., 3., 4.], [ 2., 3., 4.], [ 2., 3., 4.]])