1

I have some data of the form {{x1, y1}, {x2, y2}, ..., {xn, yn}}. It is already sorted by x values. I am looking for a simple way to resample it and obtain {{rx1, ry1}, {rx2, ry2}, ...} for a given set of {rx1, rx2, ...} coordinates, in such a way that the ry value corresponding to an rx will be the same as the y value of the nearest left x neighbour of rx.

Suppose the data is

data={{0, 1}, {1, 2}, {3, 3}, {4.5, 5}}

Then I am basically looking to take values from the function plotted below, for an arbitrary set of x values:

ListPlot[{{0, 1}, {1, 2}, {3, 3}, {4.5, 5}}, InterpolationOrder -> 0, 
 Joined -> True, PlotMarkers -> Automatic]

enter image description here

Is there anything built in for this?

Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
  • 3
    Possible duplicate: How can the behavior of InterpolationOrder->0 be controlled?. Especially the last answer seems to provide an "almost-builtin" solution by negating the x axis twice: Plot[Interpolation[{-#, #2} & @@@ InterpolationOrder -> 0][-x], {x, 0, 4.6}, PlotRange -> {0, 5}] – Lukas Lang Nov 22 '22 at 23:04
  • @LukasLang Maybe I've been writing too much C recently, but I found it frustrating that this task would be very straightfoward in a procedural language, requiring a single loop through the arrays. But in Mathematica the performance would be bad, and Nearest (i.e. a binary search for each point) feels like a huge overkill ... – Szabolcs Nov 30 '22 at 14:35
  • Yeah, this is certainly a case where a procedural approach is way more suited than a "Mathematica-style" approach (you could of course just implement the procedural approach in MMA and compile it if needed, but that's not really the point). I tried to come up with an elegant & efficient MMA-style solution, but I couldn't really think of something. I think I've seen this type of problem before, and I feel that the need for some kind of iteration state doesn't lend itself to functional solutions. The closest is something based on one of the Fold* variants, but those quickly become unreadable. – Lukas Lang Nov 30 '22 at 21:47

0 Answers0