akki
akki

Reputation: 57

Remove rows from an array that meet particular criteria MATLAB

I have an array with several rows and two columns with integers as elements. I want to remove rows that contain elements that are not present in both the columns. For example I have a matrix A, as given below

   1   2
   1   6
   7   1
   4   7
   6   4
   9   1
   6   2

See that all elements except 2 & 9 are present in both the columns. So I want to remove row 1, row 6 and row 7 which gives the output

1   6
7   1
4   7
6   4

What I could think of is to form a list which contains elements that are not present in both the rows and for each element in the list find the rows in array 'A' that contains this number and remove the row from array by making each row to remove = [ ].

I have to perform this operation on an array with millions of rows and the above procedure is taking a lot of time. Please help with a method that is more efficient in time.

Cheers.

Upvotes: 0

Views: 52

Answers (1)

Suever
Suever

Reputation: 65460

You could use ismember to determine if members of each column are in the other column (or not).

% Find the elements in column 2 that are present in column 1 AND
% elements in column 1 that are present in column 2.

toKeep = ismember(A(:,2), A(:,1)) & ismember(A(:,1), A(:,2));
B = A(tokeep,:);

%   1     6
%   7     1
%   4     7
%   6     4

Upvotes: 1

Related Questions