0

I have a matrix m = np.matrix([[1, 2, 3], [4, 5, 6]]).

I extract a vector v = m[0] + m[1], so that now v == [[5, 7, 9]]. The vector's shape is (1, 3), meaning it's considered a matrix, not a vector. How can I make v an actual vector, i.e something of shape (3,)?

I tried to use np.asarray(v) and np.array(v) but they don't do what I want.

Fabien
  • 11,256
  • 8
  • 40
  • 62

2 Answers2

3

Use np.squeeze(np.asarray(v)). So you first convert to an array (which other than matrices can have arbitrary n dimensions), then get rid of the extra dimension.

...or avoid using np.matrix in the first place, sparing you the extra step.

xdurch0
  • 8,756
  • 4
  • 27
  • 35
3

I guess the shortest would be

m.A.sum(0)
# array([5, 7, 9])

This converts to array before summing.

If you are starting from an 1xN matrix like v:

v.A1
# array([5, 7, 9])
Paul Panzer
  • 49,838
  • 2
  • 44
  • 91