User1772
User1772

Reputation: 91

How do I find the index of of the matrix row that meets a certain condition?

I have the indices (Idx = 3, 8, and 10) of two rows of an mx3 matrix A, with their associated elements as shown in A below:

A = [7 4 5
     8 4 5
     NaN NaN NaN
     1 4 5
     1 5 5
     7 4 5
     2 4 5
     4 5 7
     2 4 6
     NaN NaN NaN];

I would want to extract the row that has the last all NaNs; this could occur in any row of matrix A.

Upvotes: 0

Views: 65

Answers (1)

Sardar Usama
Sardar Usama

Reputation: 19689

Find the positions of NaNs with isnan and use all to find the rows whose all elements are NaNs. Find the elements of idx for which the the stated conditions are true and finally get the last element of idx that satisfies those conditions.

idx=idx(all(isnan(A(idx,:)),2)); %elements of idx for which A has all NaNs
idx=idx(end);                    %last element of idx for which A has all NaNs

or if you want a one-liner then use find with the direction as 'last':

idx=idx(find(all(isnan(A(idx,:)),2),1,'last'));

Upvotes: 2

Related Questions