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

16 次查看(过去 30 天)
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

采纳的回答

Star Strider
Star Strider 2019-5-28
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 个评论
Andrew Luce
Andrew Luce 2019-5-28
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 2019-5-28
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by