Lei
Lei

Reputation: 45

How to compare a matrix row by row with specified condition

I have a data matrix like this:

A=[ 5   0   10  15  0.021;
    5   0   15  20  0.011;
    10  15  5   0   0.022;
    15  20  5   0   0.009]

I need to compare each row with all of the other rows. The criteria is: If the 1st and 2nd column of this row is the same as the 3rd and 4th columns of the second row, and if the 3rd and 4th columns of the this row is the same as the 1st and 2nd column of the other row, I need the indices of these two rows.

For example:

A = [5  0 10 15  *;
     *  *  *  *  *;
     10 15 5  0  *;
     *  *  *  *  *];

As you can see:

I do not want change the order of my matrix.

Upvotes: 3

Views: 3680

Answers (1)

Gunther Struyf
Gunther Struyf

Reputation: 11168

ismember can do that:

[~,b]=ismember(A(:,1:4),A(:,[3 4 1 2]),'rows');
ind = find(b);
ind(:,2) = b(ind(:,1));

ind will contain redundant entries (eg [1 2] and also [2 1]), because your criterion is symmetrical, you can filter them using:

ind = unique(sort(ind,2),'rows')

Upvotes: 1

Related Questions