# Loop over several cuts using TCut

Hi rooters,

I want to plot a histogram and apply different cuts inside a loop, then get the mean of the histogram after each cut. What I did:

TCut icut[] = {“x<1 && x>0” , “x<2 && x>1”} ;

for (Int_t i =0 ; i<2; i++){
tree->Draw(“w>>his”, icut[i]);
Double_t y = his->GetMean();
}

However, the icut is correct only for i=0, the following values are zero.

Can anyone help me with that?

Thanks

Sheren

You did not provide a full example, so it is a little difficult to help. Here are some tips based on the for loop:

``````for (Int_t i =0 ; i<2; i++){
tree->Draw("w>>his", icut[i]);
Double_t y = his->GetMean();
}
``````

The `Draw` method will repeatedly replace the histogram with the name “his”. If you want access to it later it will be not be accessible. The declaration of `y` is scoped to the for loop and will not be accessible after the loop ends as it will have gone out of scope.

Here is an example that “works”:

``````{
//Make a tree and fill it with some random values.
TTree *tree = new TTree("tree", "Tree");
double value;
tree->Branch("x",&value);
for (int i=0;i<5000;i++) {
value = gRandom->Uniform(0,2);
tree->Fill();
}

//Create some TCuts
std::vector< TCut > cuts = {"x<1 && x>0", "x<2 && x>1"};

//Create a vector to store the histograms.
std::vector< TH1D* > hists;

//Create a canvas
TCanvas *c = new TCanvas("c","");
c->DivideSquare(cuts.size());

//Loop over the cuts and draw a histogram for each. Out put the mean.
for (int i=0;i<cuts.size();i++) {
c->cd(i+1);
hists.push_back(new TH1D(Form("h%d",i),Form("Hist %d",i), 100, 0, 2));
tree->Draw(Form("x>>h%d", i), cuts.at(i));
std::cout << "Cut " << i << " Mean: " << hists.at(i)->GetMean() << "\n";
}
}
``````

Output:

``````root [0]
Processing TCutLoop.C...
Cut 0 Mean: 0.499663
Cut 1 Mean: 1.50661
``````

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.