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?



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))
array([[ 2.,  3.,  4.],
       [ 2.,  3.,  4.],
       [ 2.,  3.,  4.]])

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

Need Your Help

UIWebView shows white bar at top and bottom when scrolling

iphone objective-c ios ipad

I have a UIWebView on top of a UIImage. When I scroll on the UIWebView, two white bars appear. 1, at the very top of the iPad window (ie the top of the UIImage, which is just a background image) an...

Fetching data from Linking Table in Hibernate

java hibernate hql

I am brand new to Hibernate and have yet to wrap my head around some of the more complex queries which are possible. So I have a super simple database schema: