A Newbie Learns (part II)
Gregory A. Landrum
landrum at foreman.ac.rwth-aachen.de
Sat Jun 19 18:21:02 CEST 1999
Continuing revelations of a learner... part II
This time with a question for the experts
---------------------------------
Matrix Multiplies
The Matrix class (part of the NumPy distribution) provides a
convenient way of dealing with matrices, so you can do stuff like:
from Matrix import *
M1 = Matrix([[1.,2.,3.,4.],[1.,2.,3.,4.],[1.,2.,3.,4.],[1.,2.,3.,4.]])
M2 = Matrix([[.1,.2,.3,.4],[.1,.2,.3,.4],[.1,.2,.3,.4],[.1,.2,.3,.4]])
M3 = M1*M2
This is considerably more convenient than using the array type
defined in the Numeric module:
from Numeric import *
M1 = array([[1.,2.,3.,4.],[1.,2.,3.,4.],[1.,2.,3.,4.],[1.,2.,3.,4.]])
M2 = array([[.1,.2,.3,.4],[.1,.2,.3,.4],[.1,.2,.3,.4],[.1,.2,.3,.4]])
M3 = matrixmultiply(M1,M2)
Unfortunately, it's also a ton slower. This is true because the
Matrix class actually calls matrixmultiply itself. So the program
ends up doing all of the work of matrixmultiply plus a bunch of
overhead to convert the matrices to arrays.
Some quick profiling indicates that using arrays instead of matrices
takes approximately half as long when doing 10000 4x4 matrix
multiplies.
So the lesson I learned is: Skip the convenience of using the Matrix
class if speed is at all important.
-------------------
After these explorations and poking around in the Numeric source, I am
left with a question. In Numeric.py, the following appears:
#This is obsolete, don't use in new code
matrixmultiply = dot
If matrixmultiply is obsolete, what exactly are we supposed to use for
doing matrix multiplies with 2D arrays? Sure, I can just call dot
myself, but that leaves the code less readable.
-greg
---------------------
Dr. Greg Landrum (landrumSPAM at foreman.ac.rwth-aachen.de)
Institute of Inorganic Chemistry
Aachen University of Technology
More information about the Python-list
mailing list