function h = dinterptable(X, Y, u) % n = length(X); % DYDX = diff(Y) ./ diff(X); % DYDX = DYDX([1, 1:end, end]); % [~, b] = histc(u, [-inf;X;inf]); % b = b - 1; % b(b == 0) = 1; % b(b == n) = n - 1; % h = DYDX(b); X = X(:); Y = Y(:); u = u(:); if numel(X) ~= numel(Y) error('dinterptable:SizeMismatch', ... 'X and Y must have the same length. Got %d and %d.', numel(X), numel(Y)); end if any(~isfinite(X)) || any(~isfinite(Y)) error('dinterptable:InvalidTable', ... 'Interpolation table contains NaN or Inf.'); end if any(diff(X) < 0) error('dinterptable:NonMonotonicX', ... 'Interpolation table X must be nondecreasing.'); end DYDX = diff(Y) ./ diff(X); DYDX = DYDX([1, 1:end, end]); [~, b] = histc(u, [-inf;X;inf]); invalid_mask = ~isfinite(u) | b < 1 | b > numel(DYDX); if any(invalid_mask) bad_values = u(invalid_mask); bad_preview = bad_values(1:min(5, numel(bad_values))); error('dinterptable:InvalidQuery', ... ['Interpolation query contains invalid values. ' ... 'num_bad=%d, sample=%s, X_range=[%g, %g], Y_range=[%g, %g].'], ... numel(bad_values), mat2str(bad_preview.'), X(1), X(end), min(Y), max(Y)); end h = reshape(DYDX(b), [], 1);