Making a 2-D histogram from two different 1-D histograms

Hi. I am very new to root and to C++ itself. I apologize in advance if this might be a stupid question, but I am trying to fill out a 2-D histogram from the contents of two 1-D histograms.

I have attached my code which is basically a root macro. The relevant portions of the macro are here:

Here’s where I declare my histograms :

TH1D *myh = new TH1D("myh","pmtrack",1000,0,0.04);
TH1D *myh2 = new TH1D("myh2","theta",1000,0.0,90.0);   
TH2D *h3 = new TH2D("h3","Number of tracks;Energy (GeV);Theta Angle (degrees)",1000,0,0.04,1000,0,90);

Here is where I fill out the two 1D histograms in the two FOR loops :

//FOR loop to go over the contents of the vectors and print them out
      for (auto const& c : mctruth_vec){
      
          std::cout << c << ' ';
          
          double myE = c.GetParticle(0).E();//Energy of incoming electron
        
          for(Int_t j=1; j<=track_vec.size(); j++)
              myh->Fill(myE);
          
          cout << "Initial Energy of the particle = "<< myE << ' '<<" GeV"<<endl;

      }
      
      //FOR loop to go over the contents of the vectors and print them out
      for (auto const& c : track_vec){
          
          std::cout << c << ' ';
          double mytheta= c.Theta(); //Theta angle of the track
          for(Int_t j=1; j<=track_vec.size(); j++)
              myh2->Fill(mytheta);
          
          cout << "Theta angle of the track = "<< mytheta << ' '<<" degrees"<<endl;

      }

Now I want to fill out the 2-D histogram with the number of tracks as a function of both energy and theta angle.I have already drawn the two 1-D histograms as seen in the screenshot attached.

But the problem is I need a FOR loop in which I can go over the contents of both the vectors , that is , mctruth_vec and track_vec. I don’t understand how can I do that in a single FOR loop. Is there a much easier way of doing this?

Please let me know if you need any more information.Thank you very much
demo_ReadHits.C (7.3 KB)

It’s a bit strange that you fill your histograms as many times as there are tracks for each track, maybe think about if that is really what you need.

About your problem, do you want each combination of elements from mctruth_vec with track_vec? In that case, just put one for loop inside another.

Or are mctruth_vec and track_vec of the same length and you want to iterate over pairs? Then the easiest way is a classic for loop with an index, so like

if (mctruth_vec.size() != track_vec.size() {
  // something is horribly wrong
}

for (unsigned int i=0; i < mctruth_vec.size(); i++) {
  auto const& mc  = mctruth_vec[i];
  auto const& track = track_vec[i];

// do something with both
}
1 Like

Maybe one of the projection function like https://root.cern.ch/doc/master/classTH2.html#a974ece9e7d260f92df00a39dba14e5b0 might help.

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