填补 2D 矩阵中指定为 "0" 的间隙,不考虑 NaN



我正在使用一个2D矩阵(全局土壤类型网格),我想填充以适合一个新的蒙版。为此,我的想法是使用最近邻插值来填补空白。我不知道如何将这种插值应用于零,而不考虑nan(代表海洋)。我在考虑手工填写这些空白,因为没有太多的空白,但我认为知道如何做到这一点很有趣。我希望网格单元代表海洋中间的岛屿,将最近的海岸视为最近的邻居,如果这有意义的话。我知道这是不现实的,但对我的目的来说已经足够了。

提前感谢你的任何想法。我不经常使用Matlab,这种东西对时间来说太有挑战性了。


我建议你使用matlab的isnan()函数。
下面是一个例子:

A = [1 0 4, 0 3 NaN, NaN 4 5, 0 0 0, NaN 1 NaN]

A =
1       0     4
0       3     NaN
NaN     4     5
0       0     0
NaN     1     NaN


通过使用isnan(A),您将返回一个矩阵,其中NaN为1,其他地方为0。

isnan(A)
ans =
     0     0     0
     0     0     1
     1     0     0
     0     0     0
     1     0     1


然后,您可以使用返回的矩阵(与A大小相同)作为其他内容的掩码和/或用您想要的任何内容替换NaN。
希望这对你有帮助!

这就是我想出来的。

function result = nonNanNearestNeighbor(A)
[gridX, gridY] = meshgrid(1:size(A,2), 1:size(A,1));
%if you don't want periodic BCs change function below
t = PeriodicBC(gridY - 1, size(A,1));
b = PeriodicBC(gridY + 1, size(A,1));
l = PeriodicBC(gridX - 1, size(A,2));
r = PeriodicBC(gridX + 1, size(A,2));
%Convert from rc notation to index notation
T = sub2ind(size(A), t, gridX);
B = sub2ind(size(A), b, gridX);
L = sub2ind(size(A), gridY, l);
R = sub2ind(size(A), gridY, r);
%Shift the stencils until they're not nans
    while any(isnan(A(T(:))))
        [tNaN, gX] = ind2sub(size(A), T(isnan(A(T))));
        T(isnan(A(T))) = sub2ind(size(A), PeriodicBC(tNaN - 1, size(A,1)), gX);
    end
    while any(isnan(A(B(:))))
        [bNaN, gX] = ind2sub(size(A), B(isnan(A(B))));
        B(isnan(A(B))) = sub2ind(size(A), PeriodicBC(bNaN + 1, size(A,1)), gX);
    end
    while any(isnan(A(L(:))))
        [gY, lNaN] = ind2sub(size(A), L(isnan(A(L))));
        L(isnan(A(L))) = sub2ind(size(A), gY, PeriodicBC(lNaN - 1, size(A,2)));
    end
    while any(isnan(A(R(:))))
        [gY, rNaN] = ind2sub(size(A), R(isnan(A(R))));
        R(isnan(A(R))) = sub2ind(size(A), gY, PeriodicBC(rNaN + 1, size(A,2)));
    end
result = (A(T) + A(B) + A(L) + A(R)) / 4;
end
function shifted = PeriodicBC(shifted, value)
    shifted(shifted <= 0) = value - shifted(shifted <= 0);
    shifted(shifted > value) = shifted(shifted > value) - value;
    if any((shifted(:) <= 0) | (shifted(:) > value))
        shifted = PeriodicBC(shifted, value);
    end
end

最新更新