How do you order table columns based on a vector with their names?

Illustration
Lucille - 2020-12-03T10:18:28+00:00
Question: How do you order table columns based on a vector with their names?

I have a table, "patients", with 5 columns. I would like these columns to follow the pattern determined by the cell, "order". How could I do this? Reproduction steps     >> load patients >> patients = table(Age,Gender,Height,Weight,Smoker,...     'RowNames',LastName); >> order = {'Gender', 'Gender', 'Age', 'Gender', 'Smoker',...     'Smoker', 'Weight', 'Height', 'Weight'};

Expert Answer

Profile picture of John Michell John Michell answered . 2025-11-20

This can be done by indexing into the table with the "order" cell.
Note: Table columns cannot repeat names so "Age" will only appear once, and all subsequent ones will have the value "Age_1", "Age_2"...
 
>> patients2 = patients(:,order)
 


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!