Sorting columns by header names
12 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
the cyclist
2023-9-7
% 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 个评论
更多回答(1 个)
Bruno Luong
2023-9-7
编辑:Bruno Luong
2023-9-7
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 个评论
Steven Lord
2023-9-7
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")
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!