[Numpy-discussion] dot function or dot notation, matrices, arrays?

David Goldsmith d.l.goldsmith@gmail....
Sat Dec 19 16:35:04 CST 2009

```I think the "bottom line" is: _only_ use the matrix class if _all_
you're doing is matrix algebra - which, as Chris Barker said, is
(likely) the exception, not the rule, for most numpy users.  I feel
confident in saying this (that is, _only_ ... _all_) because if you
feel you really must have a matrix (which I think should never really
be the case: all the operations of matrix algebra can be done w/
arrays, it's just that some look a little more elegant if the operands
are matrices) you can always cast a two-d array (or a one-d array, but
then you have to be careful about whether you're casting to a row
vector or a column vector) to a matrix - A = np.matrix(np.array(a)) -
"on the fly," so to speak.

That said, I'll be the first to acknowledge that those coming to array
programming after having come up through a pure math curriculum -
where "array" is essentially synonymous with "matrix," tensors rarely
being written out in all their gorey component glory - are confronted
with a perhaps surprising adjustment.  Since no one has yet provided
an explicit example of, IMO, the most fundamental difference between a
2-D numpy array and a numpy matrix, observe:

>>> a = np.array([[1, 2], [3, 4]])
>>> a
array([[1, 2],
[3, 4]])
>>> A = np.matrix(a)
>>> A
matrix([[1, 2],
[3, 4]])
>>> a*a           # multiplication is performed "element by element"
array([[ 1,  4],
[ 9, 16]])
>>> A*A          # standard matrix multiplication is performed
matrix([[ 7, 10],
[15, 22]])

In other words, the most fundamental difference (not the only
difference, but the one which pretty much characterizes all the
others) is the way the multiplication operator is overloaded: array
multiplication is "element by element," whereas matrix multiplication
is, well, matrix multiplication; oh, and the fact that type is
preserved, i.e., the type of an array times an array is an array, the
type of a matrix times a matrix is a matrix.  (But be careful:

>>> A*a
matrix([[ 7, 10],
[15, 22]])
>>> a*A
matrix([[ 7, 10],
[15, 22]]))

i.e., multiplication of a matrix by an array is allowed, and
regardless of order, the array operand is cast to a matrix, resulting
in matrix multiplication and a matrix-type result.)

HTH,

DG
```