MATLAB: Compare two matrices or vectors that have the same numbers but in different order

MATLABmatrix order

I wish to comapre two vectors or matrices and see if they have the same numbers but they may not be in the same order such as:
1 2 3 and 2 3 1
4 5 6 4 6 5
7 8 9 8 9 7
or
1 2 3 4 5
vs
3 4 2 5 1

Best Answer

  • The easiest way is to sort them across rows:
    A = [1 2 3
    4 5 6
    7 8 9];
    B = [2 3 1
    4 6 5
    8 9 7];
    L = all(sort(A,2) == sort(B,2),2)
    producing:
    L =
    3×1 logical array
    1
    1
    1
    Note that you get a much different result if you do not sort them.