How Does interp1 Work if the Sample Points are not Monotonic?

24 views (last 30 days)
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
ans =
matlabRelease with properties: Release: "R2025b" Stage: "release" Update: 2 Date: 16-Oct-2025
x = [1,3,0,2]; % not monotonic
y = sin(x);
xq = 1.5;
yi = interp1(x,y,xq)
yi = 0.8754
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))
ans = logical
1

Accepted Answer

Stephen23
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)
yi = 6.5000
[xz, idx] = sort(xs);
yz = ys(idx);
yj = interp1(xz, yz, xq)
yj = 6.5000
  3 Comments
Stephen23
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).
Paul
Paul on 27 Dec 2025 at 20:59
AFAICT, for a typical case interp1 will always call issorted to determine if it's necessary to sort the input.
For a sorted input that call seems to take up about 10-20% of the total runtime (which isn't that large).
N = 1e6;
x = sort(rand(N,1));
y = sin(x);
xq = 1.5;
t1 = timeit(@() interp1(x,y,xq))
t1 = 0.0029
t2 = timeit(@() issorted(x))
t2 = 5.5170e-04
t2/t1
ans = 0.1874

Sign in to comment.

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products


Release

R2025b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!