user3775806
user3775806

Reputation: 11

How to compare every row of a matrix to his uppers and lowesr neighbours rows in matlab?

I need help developing a function that compares each row of a matrix to its 5 neighbours (uppers and lowers). Two rows are identical if the 3 first elements of each row are identical.
For exapmle:

1  2  3  4 2  3  4

5  6  7  8 3  6  7

1  2  3  1 2  3  4

2 3 4  1  2   1  2

5  0  7  8 3  6  7

9  6  6  8 3  6  7

After comparing each row of this matrix to its neighbours (5 rows) we have to find that the first and the third rows are identical, because the first 3 elements of each 2 rows are identical. Thanks for helping.

Upvotes: 1

Views: 81

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

You can use bsxfun to compare each row against each other row (taking only the first three columns:

equal = squeeze(all(bsxfun(@eq, M(:,1:3).', permute(M(:,1:3),[2 3 1]))));

In your example, this gives

equal =
     1     0     1     0     0     0
     0     1     0     0     0     0
     1     0     1     0     0     0
     0     0     0     1     0     0
     0     0     0     0     1     0
     0     0     0     0     0     1

telling you that the first row equals itself and the third; the second row equals only itself, etc.

Upvotes: 2

Dan
Dan

Reputation: 45741

Let's say your matrix is called M, step one is to only consider the first 3 columns so:

m = M(:,1:3)

Next we can build a distance matrix and just choose the pairs with a distance of 0. If you have the stats toolbox then it's literally as easy as:

D = squareform(pdist(m))

If you don't have the toolbox then have a look at these answers for alternatives: Operations with arrays in Matlab

now just find the zeros:

 %//Note only lower triangular zeros are relevant
 [A, B] = find(tril(~D,-1))
 pairs = [A,B]

Upvotes: 1

Related Questions