Remove the NaN elements in a matrix
1 view (last 30 days)
Show older comments
Hi everybody, I have a problem with removing the NaN elements in a matrix, Suppose we have a matrix A of size M, N and there are some NaN elements. So I want to remove all the rows that contain NaN elements.
I wrote some commands but they do not work. Could you please check it for me?
[m n]=size(A);
for i2=m:-1:1
for i3= 1:n
if (isnan(A))
A(i2,:)=[];
end
end
end
0 Comments
Accepted Answer
Cedric
on 28 Jul 2015
Edited: Cedric
on 28 Jul 2015
A(any(isnan(A),2),:) = [] ;
To understand, evaluate
isnan( A )
any( isnan( A ), 2 )
class( any( isnan( A ), 2 ))
and you will see that the latter is a vector of logicals which flags rows that contain one or more NaN elements. We use it for indexing rows of A (logical indexing), and we set indexed rows to empty.
PS: this will work on A in one shot (so no need to iterate through rows backward. If you need to keep A unaltered, you can operate on a copy
powernew = A ;
powernew(any(isnan(powernew),2),:) = [] ;
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!