Matlab interp2() 给出 'monotonically increasing' 错误

Matlab interp2() gives 'monotonically increasing' error

我有很多代表“z”值的线,我想在它们之间的特定值处,在特定的 x 轴位置进行插值,以获得 y 值。我正在尝试 interp2() 但它抛出 'monotonically increasing' 错误。

下面的数据集是一个子集。我将它分解为 xyz-1 和 xyz-2 只是为了在这个问题中轻松绘制(即,制作一个可重复的示例)。如何修复我的 interp2() 或输入?

x1 = [0.02, 0.048, 0.108, 0.196, 0.279, 0.401];
y1 = [0.583, 0.43, 0.32, 0.279, 0.262, 0.259];
z1 = [50, 50, 50, 50, 50, 50];

x2 = [0.02, 0.048, 0.108, 0.196, 0.279, 0.401];
y2 = [0.747, 0.591, 0.435, 0.357, 0.326, 0.305];
z2 = [35, 35, 35, 35, 35, 35];

x_all = [x1, x2];
y_all = [y1, y2];
z_all = [z1, z2];

plot(x1, y1, 'blue', 'DisplayName', 'z1')
hold on
plot(x2, y2, 'magenta', 'DisplayName', 'z2')
xlabel('x') 
ylabel('y') 
legend


want_x = 0.2;
want_z = 40;

need_y = interp2(x_all, y_all, z_all, want_x, want_z, 'linear')

错误:

Error using griddedInterpolant
The grid vectors must be strictly monotonically increasing.

Error in interp2>makegriddedinterp (line 228)
    F = griddedInterpolant(varargin{:});

Error in interp2 (line 128)
        F = makegriddedinterp({X, Y}, V, method,extrap);

您可以将值插入:

x1 = [0.02, 0.04, 0.09, 0.184, 0.309, 0.667];
y1 = [0.586, 0.447, 0.34, 0.279, 0.256, 0.256];
z1 = [50, 50, 50, 50, 50, 50];

x2 = [0.022, 0.044, 0.076, 0.125, 0.184, 0.293, 0.509, 0.667];
y2 = [0.747, 0.6, 0.49, 0.41, 0.363, 0.326, 0.303, 0.3];
z2 = [35, 35, 35, 35, 35, 35, 35, 35];

want_x = 0.2;
want_z = 40;

y1_ = interp1(x1, y1, want_x);
y2_ = interp1(x2, y2, want_x);
want_y = interp1([50 35], [y1_ y2_], want_z);

这里回答了这个问题: https://www.mathworks.com/matlabcentral/answers/637955-interp2-monotonically-increasing-error

引用该答案,以防将来 link 中断:

interp2() 仅用于 two-dimensional 网格解释,不适用于矢量插值。你需要像 F = scatteredInterpolatn(x_all, z_all, y_all, 'linear'); %NOT y_all、z_all need_y = F(want_x, want_z);

函数 griddata 是您完成这些任务的好帮手,它在底层使用 scatteredInterpolant,但在我看来更加用户友好。

保持您提供的相同示例代码,将最后一行替换为:

>> need_y = griddata(x_all,z_all,y_all,want_x, want_z)
need_y =
         0.329506024096386

如果您需要查询多个点,该函数可以为 want_xwant_z 和 return 获取向量输入 need_y 的向量输出。

您还可以指定插值方法(linearcubic、等等...)。


只是为了确保它按预期工作:

>> F = scatteredInterpolant(x_all.', z_all.', y_all.', 'linear');   %NOT y_all, z_all
need_y = F(want_x, want_z)
need_y =
         0.329506024096386 % same result, yay!

关于使用griddata的更多详细信息,您可以查看my answer to this question extremely similar to yours (just worded a bit differently): Interpolation between two curves (matlab)