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")
참고 항목
카테고리
Help Center 및 File Exchange에서 Tables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!