compare two matrices or vectors that have the same numbers but in different order
15 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Andrew Luce
el 28 de Mayo de 2019
Comentada: Star Strider
el 28 de Mayo de 2019
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
0 comentarios
Respuesta aceptada
Star Strider
el 28 de Mayo de 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 comentarios
Star Strider
el 28 de Mayo de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrices and Arrays en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!