Sort a matrix based on unique values

3 visualizaciones (últimos 30 días)
Mak
Mak el 4 de Abr. de 2020
Comentada: Mak el 5 de Abr. de 2020
Hi,
Lets assume I have matrix M:
And I want to fill in matrix O:
I want to sort the final matrix based on the first row in matrix M and O. If I just fill in matrix O without sorting, I get this result:
This is wrong, because colum 3 should be NaN while column 4 should have the values from matrix O, because there is a "match" between the first rows (1004 and 1004).
I hope it was clear. Thanks
  2 comentarios
Stephen23
Stephen23 el 4 de Abr. de 2020
Use ismember.
If you had given data as text then I would have shown you how, but I can't do anything with data in screenshots.
Mak
Mak el 4 de Abr. de 2020
Hi Stephen,
Thanks for the fast response. It is just random created data. My original data is very large (857 x 19000).
But here is the code for this example:
M = NaN(4,5);
N = [1001 1002 1003 1004 1005];
M = [N;M];
O = rand(2,3);
O2 = [1001 1002 1004];
O = [O2;O];
M(2:4,1:3) = O;

Iniciar sesión para comentar.

Respuesta aceptada

the cyclist
the cyclist el 4 de Abr. de 2020
I think you can use the ismember function to do what you want. For example,
[tf,loc] = ismember([1001 1002 1004],[1001 1002 1003 1004 1005]);
will result in
loc = [1 2 4]
skipping the 3rd column as you want.
So, you probably want something like
[tf,loc] = ismember(O(1,:),M(1,:));
to find your indices.
  3 comentarios
Mak
Mak el 4 de Abr. de 2020
Editada: Mak el 4 de Abr. de 2020
I have tried this:
if ismember(M(1,:),O(1,:)) == true
M(2:5,1:5) = O
end
But did not work. It's not replacing
Mak
Mak el 5 de Abr. de 2020
This worked. Thank you
M = NaN(4,5);
N = [1001 1002 1003 1004 1005];
M = [N;M];
A = rand(3,3);
B = [1002 1003 1005];
A = [B;A];
idx = find(ismember(M(1,:),A(1,:)))
M(2:5,idx) = A

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by