Matlab:找到最后一个非 NaN 元素并将其替换为 NaN

Matlab: find last non-NaN element and replace it with NaN

如何在 Matlab 中为矩阵的每一行找到最后一个非 NaN 元素的索引并将这些值替换为 NaN?

谢谢

这个方法可能是一个实现。它使用 Logical_Array 表示 NaN 值使用“1”,non-NaN 值使用“0”。然后每行使用 find() returns 所有索引为 "0"/non-NaN 的数字。通过使用 max() 评估最大索引,可以为每个相应的行检索 last/greatest 列。取最大值可以容纳 NaN 值分散的情况。

Matrix = [1 2 NaN 4 5;
         1 NaN 3 NaN 5;
         1 2 NaN NaN NaN];
     
[Matrix_Height,~] = size(Matrix);

Logical_Array = isnan(Matrix);

for Row = 1: +1: Matrix_Height
    
    Target_Row = Logical_Array(Row,:);
    [Minimum,Indices] = find(Target_Row == 0);
    Last_Non_NaN_Index = max(Indices);
    Matrix(Row,Last_Non_NaN_Index) = NaN;
    
end

Matrix

测试矩阵的结果:

第 1 行:5 → NaN
第 2 行:5 → NaN
第 3 行:2 → NaN

运行 使用 MATLAB R2019b

x 视为:

x = [1   2   3   nan;
     3   4   nan nan;
     1   nan nan nan;
     nan nan nan nan]

您可以获得每行第一个 nan 值的索引:

[~,ind]=max(isnan(x),[],2);

然后使用 sub2ind :

x(sub2ind(size(x),max(ind.'-1,1),1:length(x))) = nan

或者 one-liner:

x((circshift(isnan(x),-1)+isnan(x))>0)=nan