Sorting columns by header names
21 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi,
I have a table with mess up data location like this.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1476296/image.png)
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 commentaires
Réponse acceptée
the cyclist
le 7 Sep 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 commentaires
Plus de réponses (1)
Bruno Luong
le 7 Sep 2023
Modifié(e) : Bruno Luong
le 7 Sep 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 commentaire
Steven Lord
le 7 Sep 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")
Voir également
Catégories
En savoir plus sur Tables dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!