1.3.5.2. TMatrixD <-> array conversion
This section describes how to convert a TMatrixD into a numpy.array and vice-versa. A breakdown
of the macro show below can be found in Macro “howtoConvertTMatrixDArray.py”
"""
Example of TMatrix into numpy array conversion
"""
import numpy as np
import ROOT
# define the number of rows and columns
nrow = 3
ncol = 5
# Initialise and fill a TMatrixD
InMat = ROOT.TMatrixD(nrow, ncol)
for i in range(nrow):
for j in range(ncol):
InMat[i][j] = ROOT.gRandom.Gaus(0, 1)
print("Original TMatrixD")
InMat.Print()
# Create the ndarray with the good shape
mat_version = np.frombuffer(InMat.GetMatrixArray(), dtype=np.float64,
count=nrow*ncol).reshape(nrow, ncol)
print("Numpy array transformation")
print(mat_version)
# Back to another TMatrixD
OutMat = ROOT.TMatrixD(nrow, ncol)
OutMat.SetMatrixArray(mat_version)
print("\nRecreated TMatrixD")
OutMat.Print()
The macro shown above, is an example of how to convert the content stored in a TMatrixD but also
how to go from a numpy.array back to TMatrixD if one needs to provide this to an Uranie’s
method. Its result is discussed in Macro “howtoConvertTMatrixDArray.py”.