Getting content of sub-range of a histogram and set in a new one

Hi ROOTers,
I have a histogram with variable binning and I want set sub-range of its content into a new one. I thought of using SetRangeUser(min,max) but then I realized that this method only affects the visualization but not the object itself. So I try to make a code to do that

void trucateHisto()
{
    TFile *file = new TFile("file.root", "read");

    TH1D *histo = (TH1D *)file->Get("myhisto;1");
    // the original histo hasthe following binning
    // double binningOld[] = {5, 10, 20, 30, 40, 50, 60, 70, 80, 100, 120, 140, 200, 250};
    double binning[] = {10, 20, 30, 40, 50, 60, 70, 80, 100, 120, 140}; // binning of the new histo
    int nBins = sizeof(binning) / sizeof(binning[0]) - 1;

    TH1D *histoNew = new TH1D("histoNew", "histoNew", nBins, binning);

    for (int i = 1; i < histo->GetNbinsX(); i++)
    {
        double cont = histo->GetBinContent(i);
        double err = histo->GetBinError(i);

        for (int j = 1; j < histoNew->GetNbinsX(); j++)
        {
            histoNew->SetBinContent(i + 1, cont);
            histoNew->SetBinError(i + 1, err);
        }
    }
    histo->Draw();
    histoNew->SetLineColor(kRed);
    histoNew->Draw("same");
}

I think I must be doing something wrong in my loop because when I draw the two histograms I see a shift in the new histogram. Any help is highly appreciated.
file.root (4.0 KB)

Hi,

what is the meaning of this innermost for loop?

Your j iterator is never used in it, so why bother?

Finally, the

in the outermost loop should really become

for (int i = 1; i <= histo->GetNbinsX(); i++)

As @yus pointed your current implementation has several inconsistencies.
There is several ways to achieve this.
A possible one is:

{
   auto file = new TFile("file.root", "read");

   TH1D *histo = (TH1D *)file->Get("myhisto");
   double binning[] = {10, 20, 30, 40, 50, 60, 70, 80, 100, 120, 140}; // binning of the new histo
   int nBins = sizeof(binning) / sizeof(binning[0]) - 1;

   auto histoNew = new TH1D("histoNew", "histoNew", nBins, binning);

   int j =1;
   for (int i = 1; i < histo->GetNbinsX(); i++) {
      double cont = histo->GetBinContent(i);
      double err = histo->GetBinError(i);
      if (histo->GetXaxis()->GetBinLowEdge(i) >= histoNew->GetXaxis()->GetXmin() &&
         histo->GetXaxis()->GetBinLowEdge(i) < histoNew->GetXaxis()->GetXmax() ) {
         histoNew->SetBinContent(j,cont);
         histoNew->SetBinError(j,err);
         j++;
      }
   }
   auto C = new TCanvas();
   C->SetLogy();
   histo->Draw("hist");
   histoNew->SetLineColor(kRed);
   histoNew->SetLineWidth(3);
   histoNew->Draw("same hist");
}