如何找到具有负值的索引并将该值替换为最接近的恰好为正的索引值?

How to find indices with a negative value and replace the value with the nearest index's value that happens to be positive?

我知道如何从矩阵中找到负值的索引。

matrix(matrix<0) = %something should be done;

但不知道如何将它们的值替换为最近的恰好为正的索引值。

  1. 这里最近的索引应该在观察索引所在的同一行。

  2. 如果该行中没有索引为正值,则应为该行的每个索引插入 0。

  3. 如果同一行中有多个索引与观察到的索引最近,则选择正确的。

  4. 我正在处理 1003x1170 单矩阵。因此,如果解决方案没有那么多的开销,那将是最好的。

例如,

[-255  4  6; 
   -5 -4  5; 
 -400  3  6; 
   -6 -7 -8;
    3 -5  4] 

变成

[4 4 6; 
 5 5 5; 
 3 3 6;
 0 0 0;
 3 4 4]

这是一个可能的解决方案:

  • 从右到左迭代列。
  • 用右边的值替换列中的每个负值。
  • 确保最右边的列(过去的矩阵边界)用零初始化。

代码示例:

A = [  -255     4     6
         -5    -4     5
       -400     3     6
         -6    -7    -8
          3    -5     4];

[rows, cols] = size(A);

P = zeros(rows, 1); %Column to the right of c initialize to zeros (like padding right side of A with zeros column).

%Loop over columns from right to left
for c = cols:-1:1
    if c < cols
        P = A(:, c+1); %Column to the right of c - assumed to be all positive (or zeros).
    end

    C = A(:, c); %Column c.
    C(C < 0) = P(C < 0); %Replace negative elements with elements from right column (all elements in P are positive or zeros).
    A(:, c) = C; %Replace column in C
end

结果:

A =

     4     4     6
     5     5     5
     3     3     6
     0     0     0
     3     4     4

可以使用fillmissing函数来实现,如下:

  1. 将负值替换为 NaN。这是必需的,因为对于 singledouble 输入,fillmissingNaN 条目视为缺失值。
  2. fillmissing'nearest' 选项一起使用,并沿维度 2 进行操作。如果有两个等距的数据值,fillmissing 显然 选择右边的那个(我还没有找到这个记录,而且我无法从源代码)。
  3. 将任何剩余的 NaN 值(对应于不包含非负值的行)替换为 0

matrix = [-255 4 6; -5 -4  5; -400 3 6; -6 -7 -8; 3 -5 4];  % data
matrix(matrix<0) = NaN;                                     % step 1
matrix = fillmissing(matrix, 'nearest', 2);                 % step 2
matrix(isnan(matrix)) = 0;                                  % step 3