The solution to sorting table columns according to a desired order is below. However, your current method requires that the variable has a certain name and this is not recommended. A variable name should never be used in code. Variable names are merely a way for humans to organize their data and quickly understand what a variable is. The code should never rely on the name of a variable. I've therefore changed the way you are forming the table so that your variable names are not used by the code.
p = [1:3]';
q = {'A';'B';'C'};
r = {'A';'B';'C'};
t = table(p,q,r,'VariableNames',{'x', 'a', 'o'});
desired_order = {'a', 'v', 'o', 'v', 's', 'x'};
[~, varOrder] = ismember(t.Properties.VariableNames, desired_order);
[~, resortOrder] = sort(varOrder);
t = t(:,resortOrder)
[addendum]
In the above solution, case matters. If a column header is named 'X' (upper case) it will not be sorted based on the index of 'x' (lower case). If you'd like to ignore case, you can use lower() to make sure the matching is all done in lower case no matter what case your headers are in.
Example:
[~, varOrder] = ismember(lower(t.Properties.VariableNames), desired_order);
0 Comments
Sign in to comment.