How do we sort one column of an alpha-numeric table and make the other columns to adjust accordingly?

2 visualizaciones (últimos 30 días)
INTRO: I import an alpha-numeric table A with the commands below:
fid = fopen('TEST_SORT.txt');
A= textscan(fid,'%f %f %s');
fclose(fid);
A=
9 5 G
1 4 B
4 3 E
2 2 D
6 1 C
3 0 I
0 9 A
7 8 H
5 7 F
8 6 J
GOAL: (1) I want to sort the rows of column 1 ascending and wish that the rows of column 2 and 3 adjust according to the sorted column 1;
(2) I want to sort the rows of the alpha-numeric column 3 and wish that the columns 1 and 2 adjust according to the sorted column 3.
PROBLEM: If I write
B=sort(A,1);
I obtain the following error:
Error using sort
DIM and MODE arguments not supported for cell arrays.
I read the documentation of sorting but it was not clear how the instructions apply to this specific situation.
I wonder if someone could help me to fix this problem.
Thank you in advance for your attention
Emerson

Respuesta aceptada

Matt Fig
Matt Fig el 5 de Oct. de 2012
Editada: Matt Fig el 5 de Oct. de 2012
When I import as you explain, I get this:
A =
[10x1 double] [10x1 double] {10x1 cell}
So if your A does not look like that, you have to tell us what it does look like.
Question 1:
[A1s,I] = sort(A{1});
B = {A1s,A{2}(I),A{3}(I)}
Now look:
[num2str(A{1}) num2str(A{2}) char(A{3})]
[num2str(B{1}) num2str(B{2}) char(B{3})]
Question 2:
[A3s,I] = sort(A{3});
B = {A{1}(I),A{2}(I),A3s}
Now look:
[num2str(A{1}) num2str(A{2}) char(A{3})]
[num2str(B{1}) num2str(B{2}) char(B{3})]

Más respuestas (1)

Thomas
Thomas el 5 de Oct. de 2012
I guess this is what you need
a={9 5 'G'
1 4 'B'
4 3 'E'
2 2 'D'
6 1 'C'
3 0 'I'
0 9 'A'
7 8 'H'
5 7 'F'
8 6 'J'}
%to sort according to column 1
out1=sortrows(a,1)
%to sort according to column 3
out2=sortrows(a,3)
  1 comentario
Emerson De Souza
Emerson De Souza el 5 de Oct. de 2012
Hi Tom, thanks for your attention.
If I write the matrix per hand as you have done above using ' ' for the third column, then you're right and it does what I wanted. However, when I IMPORT the alpha-numeric file the third column does not contain ' ' before and after the letter.
And if I run your commands, I obtain:
Error using sortrows>sort_cell_back_to_front (line 131)
Some cells in X contain non-scalar values and cannot be sorted.
Error in sortrows (line 89)
ndx = sort_cell_back_to_front(x_sub, col);
If you copy,paste and save the table as I wrote above (without ' ' around the text) into a text-file, then import as above and run your lines you will see what is going on.
I hope you know a way to correct commands to enable working with imported files.
Thank you again for your help Emerson

Iniciar sesión para comentar.

Categorías

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

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by