TMatrixD element assignment


Is it possible to assign a matrix element of TMatrixD in pyROOT?
when I do e.g.

from ROOT import TMatrixD m=TMatrixD(5,5) m(2,2)=5.4
I get the error “SyntaxError: can’t assign to function call” from python.
I’m using the CVS version of ROOT (2 days old) btw.


unfortunately, it really is a syntax error: there is no such thing as assignment to a reference return value in python. Thus, the only way to make it work is to change the language, which can be done, but I don’t think I want to go there. Note that I’ve got making ‘m[2][2] = 5.4’ work on the todo list, but there are some unresolved, but not unsurmountable, language problems with that as well.

For now (and yes, I understand that this is a stop-gap, not a solution), please create an array from the python array module, fill it with the initial values, and then create the TMatrixD from that array.

from array import array from ROOT import TMatrixD elem = 5*5*[0.] elem[ 2*5 + 2 ] = 5.4 m = TMatrixD( 5, 5, array( 'd', elem ) ) print m(2,2)

On you’ll find more about efficient matrix manipulation in python. I hope to find the time to make the scipy tools and PyROOT interoperate seamlessly (last time I checked, scipy didn’t follow python standards, such as buffer interfaces, to the letter).


thanks for the quick answer!
this works without a problem and is sufficient for what i’m doing - i can get the matrix into a python array with GetMatrix2Array, manipulate it in python and write it back with SetMatrixArray



new code has been added to CVS to allow:

[code]>>> from ROOT import TMatrixD

m = TMatrixD(5,5)
print m[2][2]
m[2][2] = 5.4
print m[2][2]

The code automatically creates bindings for all operator that return a simple builtin type by reference. Thus, it immediately works for other matrix/vector classes as well.

As said, there are language problems with this (I still don’t see how to get const correctness in the above code, unless bindings are written out by hand), but I think as is current, it is acceptable.

Thanks for using,