Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 45 ยท Data Types and Text

Tables and Maps

Learn MATLAB table variables and containers.Map key-value lookups, grouping, sorting and what Octave does differently, with pandas and dict stand-ins.

You now have three ways to hold mixed data: cell arrays by position, structs by field name, and plain matrices for numbers. Two more containers cover situations those handle awkwardly. A table stores column-oriented data, like a spreadsheet, where each column has a name and its own type. A map (containers.Map) stores values you look up by a key, such as a word or an ID.

Tables are a MATLAB feature that is not part of core Octave, so this lesson also shows how to write code that survives the move. Maps exist in both programs with a very similar interface.

Everything marked matlab is read-only on this site. The runnable examples use Python's pandas for tables and plain dictionaries for maps. They behave like the MATLAB code, but they are stand-ins, not MATLAB.

Pick the right container

Table Named columns, mixed types, many rows.
Map Look up a value by key.
Struct A few named fields for one record.
Matrix Numbers of one type, math ready.
1 / 2

Tables in MATLAB

A table looks like a matrix with column names. Unlike a matrix, each column may have its own type: text in one, numbers in another, dates in a third. Every column must have the same number of rows.

MATLAB
Name = ["Ada"; "Grace"; "Kat"; "Mae"];
Age  = [36; 45; 33; 40];
City = ["Rome"; "Oslo"; "Rome"; "Oslo"];
T = table(Name, Age, City)
%     Name      Age    City
%    _______    ___    ______
%    "Ada"      36     "Rome"
%    "Grace"    45     "Oslo"
%    "Kat"      33     "Rome"
%    "Mae"      40     "Oslo"

The variable names become the column names. You can read a column with dot syntax, and a row with parentheses:

MATLAB
T.Age                 % [36; 45; 33; 40]   (a plain column vector)
T(2, :)               % the second row, still a table
T{:, 'Age'}           % braces give the raw array, like cells
height(T)             % 4 rows
width(T)              % 3 variables
T.Senior = T.Age > 38 % add a new column

Parentheses return a table, and braces or dot syntax return the contents. That is the same box-versus-contents idea you met with cells.

Sorting, filtering and summarizing

Tables work with the logical indexing you already know, plus a few higher-level functions:

MATLAB
older = T(T.Age > 35, :)             % rows where Age > 35
sorted = sortrows(T, 'Age', 'descend')
stats = groupsummary(T, 'City', 'mean', 'Age')
%    City      GroupCount    mean_Age
%   ______    __________    ________
%   "Oslo"        2           42.5
%   "Rome"        2           34.5
summary(T)                            % per-column overview

groupsummary splits the rows by a column and applies a function to each group. It needs a recent MATLAB release; older ones use varfun or splitapply for the same job.

Reading files into tables

readtable('people.csv') reads a delimited text file, uses the header row for the variable names and guesses the type of each column. writetable(T, 'out.csv') saves it. See Reading and Writing Files for the full story, including readmatrix for all-numeric data.

Python A table with pandas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The pandas output has an index column on the left (0 to 3) that MATLAB tables do not have. Everything else maps closely: named, typed columns, boolean row filters, sorting and grouped means. The groupby result shows Oslo at 42.5 and Rome at 34.5, the same numbers groupsummary would produce.

Tables in Octave

Core Octave does not have a table type. If you open a MATLAB script that uses table, readtable or groupsummary in Octave, it stops with an undefined-function error. There are three practical options:

  • A struct of columns. Keep each column as a field holding a vector, so data.Age(2) is the second age. A struct array (one struct per row) also works.
  • A matrix plus labels. Store numeric data in a matrix and column names in a cell array.
  • An add-on package. Community packages provide table-like and dataframe-like classes (see Simulink, Toolboxes and Octave Packages for how packages are loaded). Check the package list for your Octave version, since availability changes.

If code must run in both programs, put table handling in one small file and keep the rest numeric.

Maps: values by key

A containers.Map is a lookup table. You give it a key and get the value back. Keys are usually text or numbers, and a map keeps its keys sorted.

MATLAB
stock = containers.Map();            % empty, keys are char
stock('apple')  = 12;
stock('pear')   = 7;
stock('banana') = 20;

stock('pear')                % 7
stock.isKey('plum')          % 0 (false)
stock.Count                  % 3
keys(stock)                  % {'apple', 'banana', 'pear'}  sorted
values(stock)                % {12, 20, 7}
remove(stock, 'pear');

Create one with data in a single call: m = containers.Map({'a', 'b'}, [1 2]). For numeric keys, tell the constructor the key type: containers.Map('KeyType', 'double', 'ValueType', 'any'). Asking for a missing key is an error, so test with isKey first.

Two details matter. First, a map is a handle object: if you write b = stock, both names point to the same map, and changing one changes the other. Ordinary arrays, structs and tables copy instead. Second, containers.Map exists in Octave with the same core methods (isKey, keys, values, remove, Count), though a few advanced options differ, so keep to the basics for portable code.

A typical use: counting words

MATLAB
words = {'to', 'be', 'or', 'not', 'to', 'be'};
counts = containers.Map();
for i = 1:numel(words)
    w = words{i};
    if isKey(counts, w)
        counts(w) = counts(w) + 1;
    else
        counts(w) = 1;
    end
end
keys(counts)      % {'be', 'not', 'or', 'to'}
values(counts)    % {2, 1, 1, 2}
Python Counting with a dictionary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The final lines reproduce the handle behavior: changing alias also changed counts. Python dictionaries behave like handle objects too, which is a useful hint when reading MATLAB map code. The one difference to remember is ordering: MATLAB sorts the keys, Python does not, so the stand-in sorts them explicitly.

Which container should I use?

  • Same-type numbers with math: a matrix.
  • A record with named parts: a struct. Many records, same fields: a struct array, or a table in MATLAB.
  • Spreadsheet-like data with mixed column types: a table (MATLAB only).
  • Items of different sizes: a cell array.
  • Lookup by arbitrary key: a containers.Map.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In MATLAB, what does T.Age return when T is a table with a numeric Age column?

    Dot syntax returns the contents of the variable. Parentheses, such as T(:, 'Age'), would return a table.
  2. 2. Which statement about tables is true?

    Columns may differ in type but must be equally long. Core Octave has no table type, and sortrows sorts tables by a column.
  3. 3. After b = stock, where stock is a containers.Map, you run b('kiwi') = 3. What happens to stock?

    containers.Map is a handle object. Assigning it to another variable shares the same underlying map instead of copying it.
  4. 4. What should you do before reading stock('plum') when you are not sure the key exists?

    Reading a key that is not in the map raises an error, so check with isKey first.

Summary

  • A MATLAB table holds named, typed columns of equal length; dot syntax returns contents and parentheses return a sub-table.
  • Use sortrows, logical row filters and groupsummary for everyday data analysis; readtable loads files.
  • Core Octave has no table; use a struct of columns, a matrix with labels or an add-on package.
  • containers.Map maps keys to values, keeps keys sorted, and is a handle object that is shared, not copied.
  • Guard lookups with isKey, and prefer simple containers when code has to run in both MATLAB and Octave.

Next: if, switch and Loops, where you'll start controlling the flow of your programs.