填补指定为" 0"在2D矩阵中没有考虑NaN

时间:2015-07-09 11:44:40

标签: matlab constraints nan nearest-neighbor

我正在使用2D矩阵(全局土壤网格),我想填充以适应新的面具。为此,我的想法是使用最近邻居的插值填充空白。我不知道如何将插值仅应用于零,而不是考虑NaN(代表海洋)。我正在考虑手工填充这些空白,因为它们的数量太多,但我认为无论如何知道如何做到这一点很有意思。我想要代表海洋中部岛屿的网格单元,将最近的海岸视为最近邻居,如果这是有意义的话。我知道这不现实,但为了我的目的已经足够了。

提前感谢您的任何想法。我经常不和Matlab一起玩,这种事情在时间上太过挑战了。

2 个答案:

答案 0 :(得分:1)


我建议你使用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)会返回一个带有1的矩阵,其中有NaN和0其他地方。

isnan(A)

ans =

     0     0     0
     0     0     1
     1     0     0
     0     0     0
     1     0     1


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

答案 1 :(得分:0)

这就是我想出来的。

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