How can I sort a matrix to match another matrix?

10 visualizaciones (últimos 30 días)
Doli Swey
Doli Swey el 15 de Sept. de 2020
Comentada: Doli Swey el 19 de Oct. de 2020
Hello everybody,
I have a question regarding the sorting. I have 2 matrices, A and B. For example:
A = [11 1; 12 1; 13 1; 21 2; 23 2; 31 3; 33 3; 41 4]
B = [1; 2; 1; 3; 1; 4; 2; 3]
How can I sort A (randomly each time) that the 2 column of A is same with B? Such as:
A = [12 1; 23 2; 11 1; 31 3; 13 1; 41 4; 21 2; 33 3]
Stay happy and healty..

Respuesta aceptada

Stephen23
Stephen23 el 16 de Sept. de 2020
>> [~,idx] = sort(B);
>> [~,idx(idx)] = sort(A(:,2));
>> A = A(idx,:)
A =
11 1
21 2
12 1
31 3
13 1
41 4
23 2
33 3
  6 comentarios
Stephen23
Stephen23 el 17 de Oct. de 2020
Editada: Stephen23 el 17 de Oct. de 2020
"Do you have any idea that I can make this work?"
Possibly you could replace the RHS with a string (or character vector) of the number:
A(:,2) == num2str(k)
"...the first column contains strings, whereas second column is numbers."
I strongly recommend that you convert the data into a table, then the first column would be strings and the second column really would be numbers (not strings encoding numbers). Numeric data should be efficiently stored as numeric, which also makes processing it much easier.
Doli Swey
Doli Swey el 19 de Oct. de 2020
I understand! Thank you so much. Have a wonderful day

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by