3

What's the most efficient way of checking if all rows of a matrix are numerically equal? Preferably looking for something without a for loop.

Divakar
  • 218,885
  • 19
  • 262
  • 358
James
  • 30,496
  • 19
  • 86
  • 113
  • @hagubear Similar, but different. That answer doesn't answer this question without modification. – James Dec 17 '14 at 21:51
  • @James - I find that the accepted answer is what you're looking for in that duplicate link. You just have to do an extra step and check to see if all values in the resulting vector are `true`. – rayryeng Dec 17 '14 at 22:33

4 Answers4

7

Find difference between consecutive elements across columns with diff(..,1) and then detect if all such differences are zeros with nnz(..)==0, giving us a easy-peasy-chessy one-liner and pretty efficient solution -

isallrowsequal = nnz(diff(A,1))==0                      %// A is input matrix
Divakar
  • 218,885
  • 19
  • 262
  • 358
4

You could go with: Do all components of all rows equal the first row?

allRowsEqual = all(all(bsxfun(@eq, A, A(1,:))));

On the other hand, you might be faster using a simple for loop, as the above will have to look at the entire matrix...

allRowsEqual = true;
for k = 1:size(A,1)
    if any(A(k,:)~=A(1,:))
        allRowsEqual = false;
        break;
    end
end

If you want to go for clarity, this one basically reads: Is there only one unique row?

allRowsEqual = size(unique(A,'rows'),1)==1;
knedlsepp
  • 6,065
  • 3
  • 20
  • 41
1

Another method I can suggest is to use ismember, and check to see if all values in the resulting vector are 1:

allRowsEqual = all(ismember(A, A(1,:), 'rows'));

How ismember works for the rows flag is that this will output a logical vector where 1 would denote the rows of A that matched up with A(1,:) (or the first row of A) and 0 otherwise. To ensure that all rows are the same, you would just have to check to see if all values in this logical vector are 1 and if that's the case, then every single row in your matrix is equal to each other.

rayryeng
  • 102,964
  • 22
  • 184
  • 193
0

you can check it this way for example:

suppose you have two matrices a and b ;

a =

 1     2     3
 4     5     6
 7     8     9

b =

 1     4     7
 2     5     8
 3     6     9

you can check whether the corresponding rows are equal using " sum " :

sum(a-b)

ans =

 6     0    -6

but if you try it for two equal ones you'll have all the columns of the resulting vector equal to zero:

sum(a-a)

ans =

 0     0     0

then you can check if the resulting vector equals to a vector of zeros of the same size.

  • This will yield lots of false positives! Say: `A=[0,0;0,0]` `B=[1,1;-1,-1]`. They are not equal, but still give `[0 0]`. If you really wanted to compare two matrices this way, you would have to use: `sum(abs(a-b))`, or better: `sum(a~=b)`. – knedlsepp Dec 18 '14 at 17:16