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

时间:2020-10-29 21:05:34

标签: matlab loops matrix nan

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

谢谢

enter image description here

2 个答案:

答案 0 :(得分:3)

此方法可能是一种实现。它使用Logical_Array表示使用“ 1”的NaN值和使用“ 0”表示的non-NaN值。然后,使用find()的每一行将返回所有值为“ 0” / non-NaN的索引。通过使用max()评估最大索引,可以为每个相应的行检索最后/最大列。取最大值可以容纳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

Results Image

使用MATLAB R2019b运行

答案 1 :(得分:1)

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

还是一线:

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