Tables
Real data usually comes as columns of different types: a name (text), an age (number), a start date, a department. A numeric matrix can't hold text, and a cell array doesn't know which column is which. MATLAB's answer is the table (R2013b and later): a container of named, equal-length columns, much like a spreadsheet, an R data frame or a pandas DataFrame.
Note: Octave 11 has no
tableclass (and noreadtable). The table examples below show MATLAB's output. Afterwards, the lesson builds the same workflow from structures and cell arrays, which runs in both MATLAB and Octave.
Creating a table
Pass column vectors of equal height to table and name them with 'VariableNames' (in a table, columns are called variables):
% MATLAB only
Name = {'Ann'; 'Bob'; 'Cy'; 'Dee'; 'Eve'};
Dept = {'Eng'; 'Sales'; 'Eng'; 'Eng'; 'Sales'};
Age = [31; 27; 45; 38; 29];
Salary = [5200; 4100; 6100; 4300; 4100];
T = table(Name, Dept, Age, Salary)MATLAB output:
T =
5×4 table
Name Dept Age Salary
_______ _________ ___ ______
{'Ann'} {'Eng' } 31 5200
{'Bob'} {'Sales'} 27 4100
{'Cy' } {'Eng' } 45 6100
{'Dee'} {'Eng' } 38 4300
{'Eve'} {'Sales'} 29 4100 When you build a table from variables, their names become the column names automatically. height(T) and width(T) give the number of rows and columns, T.Properties.VariableNames lists the names, and head(T, n) shows the first rows.
Getting data out
There are three kinds of indexing, and the difference matters:
| Syntax | Returns |
|---|---|
T.Age |
The contents of one column (here a numeric column vector) |
T(rows, vars) |
A smaller table |
T{rows, vars} |
The contents of those cells, concatenated into an array |
% MATLAB only
mean(T.Age)
T(T.Age > 30, {'Name', 'Age'})
T{2, 'Salary'}MATLAB output:
ans =
34
ans =
3×2 table
Name Age
_______ ___
{'Ann'} 31
{'Cy' } 45
{'Dee'} 38
ans =
4100Logical indexing with a condition on one column filters the rows, exactly as with arrays (see Logical Arrays & find).
Changing a table
% MATLAB only
T.Bonus = T.Salary * 0.1; % add a column
T.Age = []; % delete a column
T = sortrows(T, 'Salary', 'descend');
T(1:2, :)MATLAB output:
ans =
2×4 table
Name Dept Salary Bonus
_______ _________ ______ _____
{'Cy' } {'Eng' } 6100 610
{'Ann'} {'Eng' } 5200 520 Other everyday functions: addvars and removevars (insert or drop columns at a position), renamevars, rmmissing (drop rows with missing values), and [T1; T2] to stack tables with the same columns.
Grouping and joining
groupsummary (R2018a) computes a statistic per group, and join matches rows of two tables by a key column:
% MATLAB only
groupsummary(T, 'Dept', 'mean', 'Salary')
Offices = table({'Eng'; 'Sales'}, {'Berlin'; 'Lyon'}, 'VariableNames', {'Dept', 'City'});
J = join(T, Offices);
J(1:2, {'Name', 'City'})MATLAB output:
ans =
2×3 table
Dept GroupCount mean_Salary
_________ __________ ___________
{'Eng' } 3 5200
{'Sales'} 2 4100
ans =
2×2 table
Name City
_______ __________
{'Cy' } {'Berlin'}
{'Ann'} {'Berlin'}Tables also connect to files: readtable('data.csv') reads a CSV straight into a table with types detected per column, and writetable(T, 'out.csv') writes one. table2array, table2struct, struct2table and cell2table convert to and from other containers.
The portable way: a struct of columns
Without the table class, the closest equivalent is a scalar structure whose fields are columns: numeric columns as column vectors, text columns as cellstr. Column access is then identical to a table (T.Age):
T.Name = {'Ann'; 'Bob'; 'Cy'; 'Dee'; 'Eve'};
T.Dept = {'Eng'; 'Sales'; 'Eng'; 'Eng'; 'Sales'};
T.Age = [31; 27; 45; 38; 29];
T.Salary = [5200; 4100; 6100; 4300; 4100];
cols = fieldnames(T)';
fprintf('%d rows, %d columns: %s\n', numel(T.Age), numel(cols), strjoin(cols, ', '));
fprintf('mean age: %g\n', mean(T.Age));
fprintf('%s earns %d\n', T.Name{3}, T.Salary(3));5 rows, 4 columns: Name, Dept, Age, Salary
mean age: 34
Cy earns 6100
What's missing is the nice display and row indexing, but both take only a few lines. structfun applies one function to every field, so selecting rows from all columns at once is a one-liner, and a small local function prints the result as a table:
T = struct('Name', {{'Ann'; 'Bob'; 'Cy'; 'Dee'; 'Eve'}}, ...
'Dept', {{'Eng'; 'Sales'; 'Eng'; 'Eng'; 'Sales'}}, ...
'Age', [31; 27; 45; 38; 29], ...
'Salary', [5200; 4100; 6100; 4300; 4100]);
rows = @(T, idx) structfun(@(col) col(idx), T, 'UniformOutput', false);
show(T)
over30 = rows(T, T.Age > 30);
fprintf('\nAge over 30:\n');
show(over30)
function show(T)
names = fieldnames(T);
fprintf('%-8s', names{:});
fprintf('\n');
n = numel(T.(names{1}));
for r = 1:n
for c = 1:numel(names)
col = T.(names{c});
if iscell(col)
fprintf('%-8s', col{r});
else
fprintf('%-8g', col(r));
end
end
fprintf('\n');
end
endName Dept Age Salary
Ann Eng 31 5200
Bob Sales 27 4100
Cy Eng 45 6100
Dee Eng 38 4300
Eve Sales 29 4100
Age over 30:
Name Dept Age Salary
Ann Eng 31 5200
Cy Eng 45 6100
Dee Eng 38 4300
Note the double braces in the struct call: as explained in Structures, a cell value would otherwise create a struct array; {{...}} stores the whole cellstr in one field.
Sorting, adding and removing columns
Sorting is "compute the order once, apply it to every column":
T = struct('Name', {{'Ann'; 'Bob'; 'Cy'; 'Dee'; 'Eve'}}, ...
'Dept', {{'Eng'; 'Sales'; 'Eng'; 'Eng'; 'Sales'}}, ...
'Salary', [5200; 4100; 6100; 4300; 4100]);
rows = @(T, idx) structfun(@(col) col(idx), T, 'UniformOutput', false);
T.Bonus = T.Salary * 0.1;
[~, order] = sort(T.Salary, 'descend');
T = rows(T, order);
top = rows(T, 1:2);
for k = 1:2
fprintf('%-4s %-6s %d (bonus %g)\n', top.Name{k}, top.Dept{k}, top.Salary(k), top.Bonus(k));
end
T = rmfield(T, 'Bonus');
disp(fieldnames(T)')Cy Eng 6100 (bonus 610)
Ann Eng 5200 (bonus 520)
{
[1,1] = Name
[1,2] = Dept
[1,3] = Salary
}
sort is stable, so the two employees earning 4100 keep their original order, just like sortrows.
Group summaries with unique and accumarray
groupsummary has a classic two-step equivalent. unique returns the group names and, as its third output, the group number of every row; accumarray then combines the values of each group:
Dept = {'Eng'; 'Sales'; 'Eng'; 'Eng'; 'Sales'};
Salary = [5200; 4100; 6100; 4300; 4100];
[groups, ~, g] = unique(Dept);
count = accumarray(g, 1);
avg = accumarray(g, Salary, [], @mean);
top = accumarray(g, Salary, [], @max);
fprintf('%-6s %5s %8s %6s\n', 'Dept', 'Count', 'Mean', 'Max');
for k = 1:numel(groups)
fprintf('%-6s %5d %8.1f %6d\n', groups{k}, count(k), avg(k), top(k));
endDept Count Mean Max
Eng 3 5200.0 6100
Sales 2 4100.0 4100
The Categorical Data lesson uses the same trick for counting categories.
Joining two tables
To look up a value from a second table, ismember returns, for every key, its position in the other table:
Name = {'Ann'; 'Bob'; 'Cy'};
Dept = {'Eng'; 'Sales'; 'Ops'};
officeDept = {'Eng'; 'Sales'};
officeCity = {'Berlin'; 'Lyon'};
[found, loc] = ismember(Dept, officeDept);
City = repmat({'(none)'}, size(Name));
City(found) = officeCity(loc(found));
for k = 1:numel(Name)
fprintf('%-4s %-6s %s\n', Name{k}, Dept{k}, City{k});
endAnn Eng Berlin
Bob Sales Lyon
Cy Ops (none)
Rows without a match get loc = 0, so they are filled with a placeholder; this is a left join. MATLAB's join would raise an error for the unmatched Ops row, and outerjoin would fill it with missing values instead.
A struct array: one element per row
The other common layout is a struct array with one element per row. It is convenient when you add or process records one at a time, and [s.field] or {s.field} collect a whole column:
s = struct('name', {'Ann', 'Bob', 'Cy'}, 'age', {31, 27, 45});
s(end + 1) = struct('name', 'Dee', 'age', 38);
ages = [s.age];
fprintf('%d people, average age %.1f\n', numel(s), mean(ages));
[~, k] = sort(ages);
disp(strjoin({s(k).name}, ' < '))
older = s(ages > 30);
fprintf('over 30: %s\n', strjoin({older.name}, ', '));4 people, average age 35.2
Bob < Ann < Dee < Cy
over 30: Ann, Cy, Dee
| Task | MATLAB table | Struct of columns | Struct array |
|---|---|---|---|
| One column | T.Age |
T.Age |
[s.age] / {s.name} |
| Filter rows | T(T.Age > 30, :) |
structfun(@(c) c(mask), T, 'UniformOutput', false) |
s([s.age] > 30) |
| Sort | sortrows(T, 'Age') |
sort + reorder every field |
[~, k] = sort([s.age]); s(k) |
| Group statistics | groupsummary |
unique + accumarray |
same, on {s.dept} |
| Add a row | [T; newRow] |
append to every field | s(end+1) = ... |
| Read a CSV | readtable |
textscan / dlmread (see CSV & Delimited Files) |
In MATLAB, table2struct(T) gives the struct array and table2struct(T, 'ToScalar', true) the struct of columns, so you can move between all three.
Learn more: Structures, CSV & Delimited Files and pandas DataFrames and groupby for the same ideas in Python.
Test yourself
For a MATLAB table T, what is the difference between T(1:3, 'Age') and T{1:3, 'Age'}?
- The first returns a 3x1 table, the second a 3x1 numeric array
- They are identical
- The first returns a numeric array, the second a table
- Only the second is valid
Which Octave-compatible pattern computes the mean salary per department?
[g, ~, idx] = unique(dept); accumarray(idx, salary, [], @mean)mean(salary, dept)groupsummary(dept, salary)sort(dept) * salary
Why does struct('Name', {{'Ann'; 'Bob'}}) use double braces?
- To store the whole cell array in one field instead of creating a struct array
- Double braces make the field read-only
- To convert the names to strings
- They are required for every struct field