首页 文章

使用线性插值来预测matlab中的值

提问于
浏览
0

我有一组数据,并希望在Matlab中使用线性插值来查找特定点的相应值 .

x = [1 2 3 4 5 6 7 8 9];
y = [1 2 3 4 5 4 2 6 8];
xq = [1:0.25:9];
vq1 = interp1(x,y,xq);
plot(x,y,'o',xq,vq1,':.');

在这样做之后,有没有办法让我找到给定y值的x的值?例如,当y = 3.5时,x =?

2 回答

  • -1

    Simple Interpolation

    你可以用另一种方式插值......

    % Your code
    x = [1 2 3 4 5 6 7 8 9];
    y = [1 2 3 4 5 4 2 6 8];
    xq = [1:0.25:9];
    yq = interp1(x, y, xq);
    
    % Interpolate your newly interpolated xq and yq to find x = x1 when y = 3.5
    x1 = interp1(yq, xq, 3.5)
    

    Finding Zeros

    这种方法更复杂,但根据您的数据,可能更适用 .

    您可以使用fzero使用某种根查找方法,并使用如下定义的函数

    % Initialise
    x = [1 2 3 4 5 6 7 8 9]; y = [1 2 3 4 5 4 2 6 8];
    % Define function, like your interpolation, which will have a zero at x=x0
    % when y = y0. 
    y0 = 3.5;
    yq = @(xq) interp1(x, y, xq) - y0
    % find the zero, intial guess must be good enough
    y0 = fzero(yq, 1)
    

    正如评论中所指出的那样,初始猜测必须是"good enough" - 这不仅仅适用于 fzero 内的收敛,而且如果在评估期间测试的x值超出了插值范围,那么它将会中断 .

    例:

    y0 = fzero(yq, 1)
    % >> Exiting fzero: aborting search for an interval containing a sign change
    %    because NaN or Inf function value encountered during search.
    %    (Function value at 0.971716 is NaN.)
    
    y0 = fzero(yq, 5)
    % >> y0 = 3.5, as expected from the input data.
    
  • 2

    那么,既然你想要使用线性插值模型来知道插值,你只需要它周围的2个样本 .

    例如,如果您想知道何时获得值 y = 3.5 ,您需要找到2个相邻点,其中一个值低于 3.5 ,另一个值高于 3.5 .

    然后所有需要的是使用Line Equation来推断 x 的精确值 .

    我想说的是,如果您只想找到某个 y 值的 x ,则无需插入所有数据 .

相关问题