1

I have a matrix T:

[ 0.2  0.4  0.4]
[ 0.8  0.2  0. ]
[ 0.8  0.   0.2]

T = numpy.mat("0.2 0.4 0.4;0.8 0.2 0.0;0.8 0.0 0.2")

I have vector v, numpy.array(73543, -36772, 36772)

v = numpy.array([ 73543, -36772, 36772])

How do I multiply the array v by the matrix T correctly in python?

thanks,

Chris

fish2000
  • 4,289
  • 2
  • 37
  • 76
Chris Rigano
  • 687
  • 1
  • 11
  • 23

2 Answers2

1

use numpy.dot, which is not quite same as * operator:

In [138]: T.dot(v) #the resulting shape is (1, 3), not (3, 1) if you don't care
Out[138]: matrix([[ 14708.6,  51480. ,  66188.8]])

In [139]: v.dot(T) #same with v * T
Out[139]: matrix([[ 14708.6,  22062.8,  36771.6]])

In [140]: T.dot(v[:, None]) #if you need the shape to be (3, 1) when doing T*v
Out[140]: 
matrix([[ 14708.6],
        [ 51480. ],
        [ 66188.8]])
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
0

Simple:

v * T

numpy overload arithmetic operates in ways that make sense most of the time. In your case, since T is a matrix, it converts v to a matrix as well before doing the multiplication. That turns v into a row-vector. Therefore v*T performs matrix multiplication, but T*v throws an exception because v is the wrong shape. However you can make v the correct shape with v.reshape(3,1) or treat v as a vector of the correct orientation with T.dot(v) or numpy.dot(T,v).

tom10
  • 67,082
  • 10
  • 127
  • 137
Thayne
  • 6,619
  • 2
  • 42
  • 67