Matlab interp2 extrapolation

泪湿孤枕 提交于 2019-12-02 12:50:06
kishan agarwal

Hey please find my code for interp2 it just take max bound values;

function vq = Linear2dInterpWithClipExtrap(x,y,v,xq,yq);

    vq = interp2(x,y,v,xq,yq);

    [XMax, idxVMax] = max(x);
    [XMin, idxVMin] = min(x);

    idxMax = xq > XMax;
    idxMin = xq < XMin;
   if ~isempty(yq(idxMax));
    vq(idxMax) = LinearInterpWithClipExtrap(y,v(:,idxVMax),yq(idxMax));
   end
   if ~ isempty(yq(idxMin))
    vq(idxMin) = LinearInterpWithClipExtrap(y,v(:,idxVMin),yq(idxMin));
   end

   [YMax, idyVMax] = max(y);
    [YMin, idyVMin] = min(y);

    idyMax = yq > YMax;
    idyMin = yq < YMin;
   if ~isempty(xq(idyMax));
    vq(idyMax) = LinearInterpWithClipExtrap(x,v(idyVMax,:),xq(idyMax));
   end
   if ~ isempty(xq(idyMin));
    vq(idyMin) = LinearInterpWithClipExtrap(x,v(idyVMin,:),xq(idyMin));
   end



function vq = LinearInterpWithClipExtrap(x,v,xq);

    vq = interp1(x,v,xq);

    [XMax, idxVMax] = max(x);
    [XMin, idxVMin] = min(x);

    idxMax = xq > XMax;
    idxMin = xq < XMin;

    vq(idxMax) = v(idxVMax);
    vq(idxMin) = v(idxVMin

);

Mad Physicist

Yes, there are two ways to get interp2 to return a meaningful value out of bounds according to the docs.

  1. Use the 'spline' interpolation method. Unlike option #2, this will actually extrapolate the data based on the boundary conditions of the spline.
  2. Specify a final extrapval parameter. This constant will be returned instead of NaN for all other interpolation methods.

Unfortunately, there does not appear to be a way to specify something like "nearest neighbor on the grid" or something like that. If the out-of bounds elements are close to the edges, perhaps you could just expand the input array. For example like this:

x = [x(1, 1), x(1, :), x(1, end); ...
     x(:, 1), x, x(:, end); ...
     x(end, 1), x(end, :), x(end, end)]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!