select columns of a table in matlab by name in matlab

Suppose you have a table tbl with column names 'Name', 'Age', 'Gender', etc. and you want to select only the columns 'Name' and 'Gender', you can do this by indexing with a cell array of column names as shown below:

main.m
% Example table
tbl = table(['John'; 'Mary'; 'Peter'], [25; 30; 35], ['M'; 'F'; 'M'], 'VariableNames', {'Name', 'Age', 'Gender'});

% Select columns by name
selectedColumns = tbl(:, {'Name', 'Gender'});
203 chars
6 lines

The resulting selectedColumns table will only have columns 'Name' and 'Gender'.

related categories

gistlibby LogSnag