1

Can't inderstand why numpy doesn't transpose matrix.

This doesn't work:

w=2
h=3
rc= np.array([[0,0,1],[0,h,1],[w,h,1],[w,0,1]])

array([[0, 0, 1],
       [0, 3, 1],
       [2, 3, 1],
       [2, 0, 1]])

rc[0].T

array([0, 0, 1])

but this works:

v_x= np.array([[0,1,2,3]])
v_x.T
array([[0],
       [1],
       [2],
       [3]])

3 Answers 3

4

Your rc[0] is not an 1x3 matrix, it's rather a vector of 3 items:

>>> rc[0].shape
(3,)

Fix its shape if you want to transpose it:

>>> np.reshape(rc[0], (1,3)).T
array([[0],
       [0],
       [1]])
Sign up to request clarification or add additional context in comments.

1 Comment

This is also the difference between np.array([0,1,2,3]) (which is its own transpose) and np.array([[0,1,2,3]]) (which, as noted in the OP, transposes into a 4x1 matrix).
2

One of the first things I ask when confronted with a problem like this is: what's the shape?

In [14]: rc.shape
Out[14]: (4, 3)

In [15]: rc[0].shape
Out[15]: (3,)

Indexing has selected a row, and reduced the number of dimensions.

But if I index with a list (or array), the result is 2d

In [16]: rc[[0]].shape
Out[16]: (1, 3)
In [19]: v_x.shape
Out[19]: (1, 4)

There are other ways of getting that shape, or even the target (3,1).

rc[0].reshape(1,-1) # -1 stands in for the known 3
rc[0][np.newaxis,:] # useful when constructing outer products

rc[0].reshape(-1,1) # transposed
rc[0][:,np.newaxis]

np.matrix is a subclass of np.array that is always 2d (even after indexing with a scalar)

rcm = np.matrix(rc)
rcm[0] # (1,3)
rcm[0].T # (3,1)

np.matrix can ease the transition if you are coming to numpy from MATLAB, especially the older versions where everything was a 2d matrix. For others it is probably better to become familiar with ndarray, and use matrix only if it adds some functionality.

Comments

1

Transpose in fact works, but not as you expected, see docs:

By default, reverse the dimensions

So, as your array is 1d, reverse do nothing with its shape:

>>> np.array([0,0,1]).T.shape
(3,)

You can add more dimensions with reshape:

>>> np.array([0,0,1]).reshape(-1,1,1).shape
(3, 1, 1)

Now, nontrivial shape can be reversed:

>>> np.array([0,0,1]).reshape(-1,1,1).T.shape
(1, 1, 3)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.