compare two matrices or vectors that have the same numbers but in different order

32 views (last 30 days)
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

Accepted Answer

Star Strider
Star Strider on 28 May 2019
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.
  4 Comments
Andrew Luce
Andrew Luce on 28 May 2019
Hello
Last caveat, what if the values were not in any order, where the values that are roughly 1 2 3 are not all contained on the first row
A=[1 2 3 B=[8.9 1.9 4.6
4 5 6 1.2 3.9 2.8
7 8 9] 8.1 7.3 5.7
Thank you for all your help
Andrew
Star Strider
Star Strider on 28 May 2019
As always, my pleasure.
This becomes a bit more complicated, and I’m not certain what result you want here. I would continue to use ismembertol, and set the tolerance depending on what you want to consider.
For example:
A=[1 2 3
4 5 6
7 8 9];
B=[8.9 1.9 4.6
1.2 3.9 2.8
8.1 7.3 5.7];
L = ismembertol(A, B, 0.025)
produces:
L =
3×3 logical array
1 1 1
1 0 0
0 1 1
This is an ‘any’ condition, where any elements of ‘A’ are within tolerance of the elements in ‘B’. You could then change the tolerance or do logical comparisons on the outputs.
Note that you can also use ismembertol with a second output that would provide more information:
[L,Locb] = ismembertol(A, B, 0.025)
producing:
L =
1 1 1
1 0 0
0 1 1
Locb =
2 4 8
5 0 0
0 3 1
The ‘Locb’ output contains the index location in ‘B’ for each element in ‘A’ that is a member of ‘B’.
In this instance, sorting the rows (or columns) would not provide any benefit.

Sign in to comment.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!