Getting (x,y) for maximum value within specific range of graph

There have been similar questions on the forum, but mostly in connection with histograms. Consider the attached picture. How could one find the point corresponding to this local maximum (see arrow)? Thanks!

Hi,

Are the point really strictly increasing? Are they ordered? If both answers are “yes” then I’d not even use TGraph but the C++ standard library: is_sorted_until is your friend!

If it’s not sorted, sort it first - but make sure to re-order both x and y values, not just the x values :slight_smile:

Let me know if you need an example code snippet.

Axel.

1 Like

Hi,
a TGraph is essentially an unordered collection of pairs (x,y).
So I’m afraid there is no other way but “brute force” looping on all points.
Otto

TGraph::Sort

Hi,
Axel and Wile are of course right, thats the elegant way.
I myself as a simple minded guy would do it straightforward:

#include "TGraph.h"

int getmax(TGraph *gr, double from, double to)
{
   double maxval = -1e20;
   int maxind =-1;
   double *x = gr->GetX();
   double *y = gr->GetY();
   for (int i=0; i<gr->GetN(); i++) {
      if (x[i] < from)
         continue;
      if (x[i] > to) 
         continue;      // replace by break if ordered
      if (y[i] > maxval) {
         maxval = y[i];
         maxind = i;
      }
   }
   if (maxind <0)
      printf("no max found\n");
   return maxind;
};

double aaa()
{
   double from = 5, to = 8.5;
   double x=0, y=0;
   auto gr = new TGraph(10);
   for (int i=0; i<10; i++){
      gr->SetPoint(i, i+2, (i%5)*i);
   }
   gr->Draw("a*");
   int mind = getmax(gr, from, to);
   if (mind >=0) {
      gr->GetPoint(mind, x,y);
      printf("Max %f at: %d\n", y, mind);
   }
   return y;
}

Otto