find rows in a matrix where all the elements (of those rows) are not NaN

16 views (last 30 days)
How to finds rows in "a" where both elements of those rows (2 in this case) are numbers and not "NaN" ?
a = [ NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
7972 8160
NaN NaN
NaN NaN
8083 8343
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN];
I have the following solution, but I am not sure if it is correct:
[rows, columns] = find(~isnan(a));
notNaN_rows = a(unique(rows),:)
notNaN_rows =
7972 8160
8083 8343
Indeed if a row in "a" contains one element as "NaN" and one element as number, for example "2291", I get something like this:
notNaN_rows =
NaN 2291
7972 8160
8083 8343

Accepted Answer

Cris LaPierre
Cris LaPierre on 1 Jul 2022
I would use Logical indexing.
a = [ NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
7972 8160
NaN NaN
NaN NaN
8083 8343
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN];
ind = sum(~isnan(a),2)==2
ind = 24×1 logical array
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0
a(ind,:)
ans = 2×2
7972 8160 8083 8343

More Answers (2)

Stephen23
Stephen23 on 5 Apr 2023
a = [NaN,NaN;NaN,NaN;NaN,NaN;7972,8160;NaN,NaN;NaN,NaN;8083,8343;NaN,NaN;NaN,NaN]
a = 9×2
NaN NaN NaN NaN NaN NaN 7972 8160 NaN NaN NaN NaN 8083 8343 NaN NaN NaN NaN
b = rmmissing(a)
b = 2×2
7972 8160 8083 8343

Bruno Luong
Bruno Luong on 5 Apr 2023
An alternative ways of testing
a = [ NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
7972 8160
NaN NaN
NaN NaN
8083 8343
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN];
a(all(a==a,2),:)
ans = 2×2
7972 8160 8083 8343

Categories

Find more on Creating and Concatenating Matrices 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!