Question

I am not sure how to phrase this question correctly, but this is what I am trying to do.

A single histogram can be plotted using cern ROOT with a following command,

(TH1F*)electron->Draw();

But I have tens of histograms named in a sequence, such as electron1, elecron2, electron3, etc, and I want to write a simple loop to plot them all. I tried using sprintf and a simple for loop, but ROOT doesn't like it.

char name[20];
(TH1F*)electron->Draw();
for(int j=0;j<5;j++){
            sprintf(name, "%s%d","electron",j);
            (TH1F*)name->Draw("same");
 }

What am I doing wrong?

Thanks in advance.

Was it helpful?

Solution

You need one additional step. As @twalberg says, you have a string, not an object pointer. For root what you can do is just change your code such that I add one additional line.

char name[20];
electron->Draw();
for(int j=0;j<5;j++){
   sprintf(name, "%s%d","electron",j);
   TH1F *h = (TH1F*)gDirectory->Get(name); // THIS IS THE MISSING LINE
   if ( h ) h->Draw("same"); // make sure the Get succeeded 
 }

The extra line gets the referenced object by name from the local TDirectory. The cast is necessary such that the gDirectory is cast to the right kind of object.

When you use root interactively this happens magically behind the scenes.

OTHER TIPS

Creating a string that says "electron0", casting the char * pointing to the beginning of the string to a TH1F *, and dereferencing it as if the character string were actually a struct TH1F * (or class TH1F *) is most likely just going to crash the program, and is not the same as referencing a variable named electron0.

Probably your best bet is to, rather than naming a bunch of variables electron0, electron1, etc..., create an array as in TH1F electron[NELECTRONS];, then reference them as electron[0], electron[1], etc. (Alternatively, if the objects are dynamically allocated, use a TH1F *electron[NELECTRONS]; and store the pointers (with appropriate indirections to reference them (*(electron[0]).Draw(...) or electron[0]->Draw(...)).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top