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

28 ビュー (過去 30 日間)
Paul
Paul 2025 年 12 月 27 日 18:50
コメント済み: Paul 2025 年 12 月 27 日 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
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

採用された回答

Stephen23
Stephen23 2025 年 12 月 27 日 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 件のコメント
Stephen23
Stephen23 2025 年 12 月 27 日 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 2025 年 12 月 27 日 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

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

製品


リリース

R2025b

Community Treasure Hunt

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

Start Hunting!

Translated by