Remove Inf and NaN values in a Point Cloud in the fastest way

308 views (last 30 days)
If I have a matrix A
A = [1, 11, 21; NaN,12, 22; 3, 13, Inf; NaN,14, NaN; 5, Inf, NaN; 6, 16, 26];
I want to eliminate all rows which have either Inf or NaN elements.
So the expected result would be : [1, 11, 21; 6, 16, 26];
Since I will be working with images of dimensions 4000 X 3000, I want a very fast and efficient way of doing this.
Thank you =)

Accepted Answer

Adam
Adam on 20 Nov 2014
A = A( ~any( isnan( A ) | isinf( A ), 2 ),: )
  3 Comments
Adam
Adam on 21 Nov 2014
Edited: Adam on 21 Nov 2014
any( A > 0 & A < 100, 2 )
will give you the indices of all rows satisfying 0 < A < 100. So
A = A( ~any( A > 0 & A < 100, 2 ), : );
will remove those rows from A.
I often prefer to do things like that in the two lines for better readability, so:
idx = any( A > 0 & A < 100, 2 );
A = A( ~idx );
That way you can also easily double-check the intermediate indexing result before it deletes the wrong rows of your matrix!
Your version was lacking a '(' somewhere, but also the ,2 argument is for the 'any' function, telling it to run on the 2nd dimension. To be honest I always get mixed up with rows and columns and dimension 1 and 2 so I just try them out until I get the right one!
Meghana Dinesh
Meghana Dinesh on 22 Nov 2014
Thank you =) I couldn't find all this explanation on tutorials. Learning to use these functions comes from experience :D

Sign in to comment.

More Answers (1)

Vignesh Kumar
Vignesh Kumar on 11 Aug 2022
%%Try this. It worked for me
A = [1, 11, 21; NaN,12, 22; 3, 13, Inf; NaN,14, NaN; 5, Inf, NaN; 6, 16, 26];
Anew=A((isfinite(A)))
Anew = 12×1
1 3 5 6 11 12 13 14 16 21

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!