1

I have a list as data which is uploaded here, due to its long length. We can consider to the list as a collection of {x,y} pairs.

Please consider a value for example 3.63, above this value we first arrive 4.814 (we called it y2), and below this value we first arrive 3.08 (we called it y1). As far as we can see, they (3.08 and 4.814) are y with any x.

I want to access {y1,y2,y2-y1} that are the nearer ys to a special value which is 3.63 here. For example I found here the triple collection is {3.08, 4.814, 1.734}.

In a plot we can show the aim as the below plot in which y1 and y2 are highlighted.

enter image description here

Inzo Babaria
  • 1,513
  • 7
  • 11

3 Answers3

5

Those two y-values that are nearest to 3.63 are extracted below along with their difference:

data = Import["rereimport.dat"];
{#, #2, #2 - #} & @@ Nearest[data[[All, 2]], 3.63, 2]
{3.08, 3.055, -0.025}'

The following gives instead one y-value above 3.63, and one below 3.63:

With[{ys = Union[data[[All, 2]]]}, {#, #2, #2 - #} & @@
   Nearest[ys, First[Nearest[MovingAverage[ys, 2], 3.63, 1]], 2]]
{3.08, 4.831, 1.751}
Coolwater
  • 20,257
  • 3
  • 35
  • 64
  • Your answer seems to have a bug. For example: SeedRandom[5]; data = RandomReal[10, {10, 2}]; near = RandomReal[10]; With[{ys = Union[data[[All, 2]]]}, Nearest[ys, Nearest[MovingAverage[ys, 2], near, 1][[1]], 2]] produces a bracket that doesn't include the target. – Carl Woll Jan 25 '18 at 03:56
3

You could use Nearest. The following answer is similar to my LeftNeighbor function from Given an ordered set S, find the points in S corresponding to another list:

Bracket[data_] := Module[{ord = Ordering[data], s},
    s = data[[ord]];
    BracketFunction[s, ord, Nearest[s->"Index"]]
];
Bracket[data_, list_] := Bracket[data][list]

BracketFunction[s_, o_, nf_][list_] := With[{n = nf[list][[1]]},
    With[{lindex=n - UnitStep[s[[n]] - list]},
        o[[{lindex, lindex+1}]]
    ]
]

BracketFunction[s_, o_, nf_][list_List] := With[{n = nf[list][[All, 1]]},
    With[{lindex=n - UnitStep[s[[n]] - list]},
        Transpose@{o[[lindex]], o[[lindex+1]]}
    ]
]

BracketFunction returns the indices of the data that bracket the input. For example:

bf = Bracket[data[[All, 2]]];
indices = bf[3.63]
data[[indices, 2]]

{391, 402}

{3.08, 4.831}

where I only return the y values here. BracketFunction also works with lists of data:

indices = bf[{2.2, 3.63}]
data[[#]]& /@ indices

{{396, 395}, {391, 402}}

{{{2.2845, 1.969}, {2.3422, 2.255}}, {{2.5731, 3.08}, {2.5731, 4.831}}}

where I return the {x, y} values this time.

If desired, one could add a SummaryBox format to BracketFunction.

Carl Woll
  • 130,679
  • 6
  • 243
  • 355
2

here is a simple way to get the nearest point above and below.

data = RandomReal[{0, 10}, 100];
SortBy[data, 1/(# - 3.08) &][[{1, -1}]]

{3.03482, 3.13265}

caveat, this throws an error if any data point exactly equals the special value.

george2079
  • 38,913
  • 1
  • 43
  • 110