Sorting columns by header names
21 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Khang Nguyen
am 7 Sep. 2023
Kommentiert: Steven Lord
am 7 Sep. 2023
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 Kommentare
Akzeptierte Antwort
the cyclist
am 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 Kommentare
Weitere Antworten (1)
Bruno Luong
am 7 Sep. 2023
Bearbeitet: Bruno Luong
am 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 Kommentar
Steven Lord
am 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")
Siehe auch
Kategorien
Mehr zu Tables finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!