Sorting columns by header names
13 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Khang Nguyen
el 7 de Sept. de 2023
Comentada: Steven Lord
el 7 de Sept. de 2023
Hi,
I have a table with mess up data location like this.
I want to bring all the same Columns letters together. I am wondering if there is an easy way to do this?
I have try to impliment bubble sort as follow but running into some compare text problem
function [table_out] = sort_text(table_in)
table_size = size(table_in(1,:)); % table size
for i = 1:table_size(2)
for j = 1:table_size(2)
if strcmp(char(table_in.Properties.VariableNames(j)), char(table_in.Properties.VariableNames(j+1))) == 1
table_in = swap(table_in(j),table_in(j+1));
end
end
end
end
0 comentarios
Respuesta aceptada
the cyclist
el 7 de Sept. de 2023
% Make up a data table
N = 3;
Column_B_data1 = rand(N,1);
Column_A_data1 = rand(N,1);
Column_C_data2 = rand(N,1);
Column_D_data2 = rand(N,1);
Column_A_data2 = rand(N,1);
Column_B_data2 = rand(N,1);
Column_D_data1 = rand(N,1);
tbl = table(Column_B_data1,Column_A_data1,Column_C_data2,Column_D_data2,Column_A_data2,Column_B_data2,Column_D_data1)
% Find the sorting order
[~,sortingIndex] = sort(tbl.Properties.VariableNames);
% Sort into a new table
new_tbl = tbl(:,sortingIndex)
0 comentarios
Más respuestas (1)
Bruno Luong
el 7 de Sept. de 2023
Editada: Bruno Luong
el 7 de Sept. de 2023
A=rand(10,1);
B=rand(10,1);
Z=rand(10,1);
T=table(Z,B,A)
[~,is]=sort(T.Properties.VariableNames);
T = T(:,is)
1 comentario
Steven Lord
el 7 de Sept. de 2023
If your table had a mostly-sorted set of variables and you only need to move one or two variables, the movevars function may be of use instead of indexing.
A=rand(10,1);
B=rand(10,1);
Z=rand(10,1);
T=table(A, Z, B)
In release R2023a and later, you can move a variable to the end by calling movevars with two inputs. For prior releases you could specify 'After' and tell MATLAB to move the variable after the last variable using the output of width on the table.
T2 = movevars(T, "Z") % Move Z to the end
T3 = movevars(T, "Z", "After", width(T))
Or if you're adding table variables incrementally, you could use addvars to add the new variable in a particular location.
C = (1:height(T2)).';
T4 = addvars(T2, C, 'After', "B")
Ver también
Categorías
Más información sobre Tables 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!