How can I find for each row of the matrix in Matlab the index of the last non-NaN element and replace these values with NaN?
Thank you
This method may be an implementation. It uses a Logical_Array
that indicates NaN
values using "1" and non-NaN
values using "0". Then each row using find()
returns all the indices that are "0"/non-NaN
number. By evaluating the maximum index using max()
the last/greatest column can be retrieved for each respective row. Taking the max allows scenarios where the NaN
values are scattered to be accommodated.
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
Row 1: 5 → NaN
Row 2: 5 → NaN
Row 3: 2 → NaN
Ran using MATLAB R2019b
Consider x
as:
x = [1 2 3 nan;
3 4 nan nan;
1 nan nan nan;
nan nan nan nan]
You can obtain the index, for each row, of the first nan
value with:
[~,ind]=max(isnan(x),[],2);
And then using sub2ind
:
x(sub2ind(size(x),max(ind.'-1,1),1:length(x))) = nan
Or the one-liner:
x((circshift(isnan(x),-1)+isnan(x))>0)=nan
x
is your matrix, then you can get the index with[~,ind]=max(isnan(x),[],2)
– obchardon