How to check if all rows of a matrix are equal

What's the most efficient way to check if all rows of a matrix are numerically equal? It is advisable to search for something without a for loop.

+3


source to share


4 answers


You can use: are all components of all rows equal to the first row?

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

      

On the other hand, you can use a simple loop faster for

, since the above will need to look at the whole 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, it basically says: is there only one unique string?

allRowsEqual = size(unique(A,'rows'),1)==1;

      

+4


source


Find the difference between consecutive elements in columns

c and then determine if all such differences are zeros in c , giving us a simple one-way and very efficient solution - diff(..,1)

nnz(..)==0



isallrowsequal = nnz(diff(A,1))==0                      %// A is input matrix

      

+5


source


Another method I can suggest is to use ismember

and check if all values ​​are in the resulting vector 1

:

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

      

As ismember

works for a flag rows

, this will output a vector logical

where 1

will denote the lines A

that match A(1,:)

(or the first line A

) and 0

otherwise. To make sure all rows are the same, you just need to check if all the values ​​in this logical

vector are not 1

, and if this is the case, then every row in your matrix is ​​equal to each other.

+1


source


you can check this 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 if the matching strings are equal using "sum":

sum(a-b)

ans =

 6     0    -6

      

but if you try it for two equals, you will have all columns of the resulting vector equal to zero:

sum(a-a)

ans =

 0     0     0

      

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

0


source







All Articles