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([, , ])
In NumPy, to do the same thing, how I can do it? One way is doing the following:
x = np.array([, , ]).transpose()
But it looks somewhat absurd. Could anyone give some suggestions on this?
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 [,,] 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 : x1d.shape Out: (3,) In : x1d[None,:].shape Out: (1, 3) In : x1d[:,None].shape Out: (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 : x1d+np.ones((3,3)) Out: array([[ 2., 3., 4.], [ 2., 3., 4.], [ 2., 3., 4.]]) In : x1d[None,:]+np.ones((3,3)) Out: array([[ 2., 3., 4.], [ 2., 3., 4.], [ 2., 3., 4.]])