
What is the best way to treat scalar values from a matrix? It seems that it's best to treat them as a simple Python values and not to leave them wrapped up in the ndarray structure. I would welcome advice. The problem is illustrated below. Colin W. # tMul.py import numpy.core as _n a= _n.arange(12).reshape((3, 4)) b= _n.arange(12).reshape((4, 3)) c= _n.dot(a, b) print `c` amat= _n.mat(a) bmat= _n.mat(b) cmat= amat*bmat print cmat print _n.dot(amat, _n.mat(5)) Output:
array([[ 42, 48, 54], [114, 136, 158], [186, 224, 262]]) [[ 42 48 54] [114 136 158] [186 224 262]] Traceback (most recent call last): File "<string>", line 74, in run_nodebug File "C:\Documents and Settings\cjw\My Documents\PyDev\PyMatrix\tMiul.py", line 11, in <module> print _n.dot(amat, _n.mat(5)) ValueError: objects are not aligned

On 1/1/07, Colin J. Williams <cjw@sympatico.ca> wrote:
What is the best way to treat scalar values from a matrix?
It seems that it's best to treat them as a simple Python values and not to leave them wrapped up in the ndarray structure. I would welcome advice.
The problem is illustrated below.
Colin W.
# tMul.py import numpy.core as _n a= _n.arange(12).reshape((3, 4)) b= _n.arange(12).reshape((4, 3)) c= _n.dot(a, b) print `c` amat= _n.mat(a) bmat= _n.mat(b) cmat= amat*bmat print cmat print _n.dot(amat, _n.mat(5))
mat(5) is a 1x1 matrix: In [5]: mat(5) Out[5]: matrix([[5]]) so the error is valid. If you want to do a scalar multiply try In [6]: amat*5 Out[6]: matrix([[ 0, 5, 10, 15], [20, 25, 30, 35], [40, 45, 50, 55]]) This is an example where using arrays, as opposed to matrices, is perhaps less confusing. Chuck

Charles R Harris schrieb:
mat(5) is a 1x1 matrix:
In [5]: mat(5) Out[5]: matrix([[5]])
so the error is valid. If you want to do a scalar multiply try
In [6]: amat*5 Out[6]: matrix([[ 0, 5, 10, 15], [20, 25, 30, 35], [40, 45, 50, 55]])
Or you can do multiply(amat, mat(5)), even when everything is a matrix, and broadcasting will work.
This is an example where using arrays, as opposed to matrices, is perhaps less confusing.
I beg to differ. This only shows that with matrices dot() will not automatically broadcast everything. IMHO that can be an advantage by preventing subtle bugs. If you want to rely on broadcasting with matrices, you could use multiply() (or kron(), depending on what you want). -sven (in his don-quijote-esque fight to keep the numpy list balanced between arrays and matrices... ;-)
participants (3)
-
Charles R Harris
-
Colin J. Williams
-
Sven Schreiber