TMatrixD as a parameter

This question is about how to return a TMatrixD object as a parameter of a function.

My main program is main.cxx and it calls function myfunc(TMatrixD a).

So in main.cxx:

TMatrixD ma(nraw, ncol);

Is the operation on “a” in myfunc going to be passed back to “ma” in main.cxx?

I did a test in interactive mode of ROOT and it does. But when I compiled the code I use in the interactive mode, operation on “a” in myfunc is not being passed back to main.cxx. Is this supposed the way how ROOT works? Or I did something wrong?

If operation in myfunc on “a” is not supposed to be passed back to “ma” by default, what am I supposed to do to let it happen?

Or I have to think of some other ways to pass the information back?


pass it by reference (TMatrixD&). Read a C++ introduction to understand what that means.

Can you show us an example macro where in interactive mode the matrix ma is changed by your method, even though it is not passed by reference?


Thanks for the help!

Actually, I found 2 things which worked in interactive mode but not in a C++ program which is going to be compiled. I only mentioned one in my previous post and the other one is “mymatrixd(i,j)”, where “mymatrixd” is a TMatrixD type pointer “TMatrixD* mymatrixd”, is legal in the interactive mode but illeagal in a C++ program.

I’m attaching the I was running.
test.cxx (1.46 KB)

change(m1,m2) changes m1 because you set m2=m1, where m2 is a pointer to a TMatrixD and m1 is a TMatrixD. This is invalid C++. Cint translates the line to “m2=&m1”, i.e. m2 will point to m1 afterwards. Thus, m1 gets changed by changing what m2 points to, in change(m1,m2). Summary: this is a problem with your code - Cint tries to help you a bit, and you see a side effect from that.

The other discrepancy between compiled and interpreted code you report is again due to your code being invalid C++. Cint “fixes” some of that, but the compiler won’t. Please check you favourite C++ book why this is the correct call to TMatrixD::operator()(int, int) const (and not what you have in your code):

TMatrixD m2 = new TMatrixD(2,2); for (Int_t i=0; i<2; i++) for (Int_t j=0; j<2; j++) cout << (*m2)(i,j) << " ";
Simply fix your code and all your problems are gone. Always take the compiler as reference, not Cint - i.e. just because Cint runs your code does not mean it’s valid.
Cheers, Axel.