본문으로 바로가기

[Python] matrix vs array class

category CAE/Enjoy Programming 2011. 10. 23. 13:05

from numpy import *

## matrix class

a=mat('1 2 3;4 5 6;7 8 9') # matrix multiply

b=mat([[10,20,30],[40,50,60],[70,80,90]]) # element-wise multiply

c=a*b

d=multiply(a,b)

print '\na=',a,'\nb=',b,'\nc=',c,'\nd=',d

## array class

a=array(a)

b=array([[10,20,30],[40,50,60],[70,80,90]])

c=dot(a,b) # matrix multiply

d=a*b # element-wise multiply

print '\na=',a,'\nb=',b,'\nc=',c,'\nd=',d

 

 

array 위주로 쓰다가 dot product 구하는게 잦아지면 matrix로 변환시켜 계산하는 식으로 혼용하면 됨

  • Many numpy function return arrays, not matrices
  • The only disadvantage of using the array type is that you will have to use dot instead of * multiply (reduce) two tensors (scalar product, matrix vector multiplication etc.).
  • The array is thus much more advisable to use, but in the end, you don't really have to choose one or the other. You can mix-and-match. You can use array for the bulk of your code, and switch over to matrix in the sections where you have nitty-gritty linear algebra with lots of matrix-matrix multiplications.