How Does interp1 Work if the Sample Points are not Monotonic?
24 views (last 30 days)
Show older comments
Paul
on 27 Dec 2025 at 18:50
Commented: Paul
on 27 Dec 2025 at 20:59
Forever I've thought that the sample points input to @doc:interp1 have to be distinct AND monotonic. But I just saw on the doc page that distinct is the only requirement.
For example:
matlabRelease
x = [1,3,0,2]; % not monotonic
y = sin(x);
xq = 1.5;
yi = interp1(x,y,xq)
I'm quite surprised by this result.
Does interp1 sort the sample points and reorder the sample values if the sample points are not monotonic?
The same answer is obtained:
isequal(yi,interp1(sort(x),sin(sort(x)),xq))
0 Comments
Accepted Answer
Stephen23
on 27 Dec 2025 at 19:48
INTERP1 automatically sorts the sample points internally if they're not monotonic, and it reorders the corresponding sample values accordingly:
xs = [3, 1, 4, 2];
ys = xs.^2; % [9, 1, 16, 4]
xq = 2.5;
yi = interp1(xs, ys, xq)
[xz, idx] = sort(xs);
yz = ys(idx);
yj = interp1(xz, yz, xq)
3 Comments
Stephen23
on 27 Dec 2025 at 20:42
"Do you recall if that's always been the behavior?"
I don't recall ever using this, nor does the documentation in the wayback machine seem to mention it.
"Any opinion on if that should be the behavior, or if such an input should throw an error?"
Does this edge-case handling takes significant processing time for all users? That would be unfortunate... but I have no idea what all the use-cases are that TMW have specified for this function (the fact that it is not documented indicates that it might not be very significant).
More Answers (0)
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!