Skip to content
LumenaryAcademy
Practice 55 min

Text, cell arrays and structs

Character arrays and the functions that handle text, cell arrays for mixed data, structs and struct arrays for records, maps, and JSON.

Code tested · 5AI-draftedAwaiting review by a computer scientist
MotivationH

Beyond numbers

Numerical work is never only numbers. Measurements come with station names and units; a simulation has parameters with names; results go into reports and file names; data arrive as text files or JSON from a web service. A matrix of doubles cannot hold "Quito, 2850 m, readings 14.2, 15.1, 13.8", because a matrix must be rectangular and of a single type.

MATLAB answers with three containers. Character arrays hold text. Cell arrays are arrays whose elements can be anything, of any size: a number, a piece of text, a matrix, another cell array. Structs group named fields into a record, and struct arrays hold many records with the same fields, a lightweight table. This lesson works through each, with the idioms people actually use, and finishes with maps and JSON for data exchange.

It is also the lesson where MATLAB and Octave diverge the most, because MATLAB has added a separate string type and a family of text functions in recent years that Octave has not implemented. Everything shown here runs in both.

Worked examplesH

Text as character arrays

Definition— Character array

A char array is a matrix of characters. 'Kuala Lumpur' is a 1-by-12 char array; you can index it, concatenate it with brackets and transpose it like any matrix. Its elements are character codes, so double('A') is 65.

matlab
place = 'Kuala Lumpur';
disp(numel(place))
disp(place(1:5))
disp(upper(place))
disp([place ', Malaysia'])
disp(strcmp(place, 'Kuala Lumpur'))
disp(strcmpi('OCTAVE', 'octave'))
disp(strrep(place, ' ', '_'))
disp(strtrim('   padded   '))
disp(fliplr('stressed'))
disp(double('Az'))
disp(char([72 105 33]))

msg = sprintf('%s has %d characters.', place, numel(place));
disp(msg)
disp(num2str(pi, 6))
disp(str2double('2.5e3') + 1)
disp(strfind('banana', 'an'))

disp(regexprep('call 555-0199 or 555-0123', '\d{3}-\d{4}', '<number>'))
pairs = regexp('x=12, y=7, z=30', '(\w)=(\d+)', 'tokens');
fprintf('%s is %s\n', pairs{2}{:});
text
12
Kuala
KUALA LUMPUR
Kuala Lumpur, Malaysia
1
1
Kuala_Lumpur
padded
desserts
    65   122
Hi!
Kuala Lumpur has 12 characters.
3.14159
2501
   2   4
call <number> or <number>
y is 7
  • Concatenate with brackets: [place ', Malaysia'].
  • Compare with strcmp, never ==. == compares character by character, so it fails with an error when the lengths differ and returns an array when they match. strcmpi ignores case; strncmp compares the first n characters.
  • Convert numbers to text with sprintf (full control, the same format codes as fprintf) or num2str (quick, with an optional precision). Convert text to numbers with str2double, which returns NaN for text that is not a number; avoid str2num, which evaluates its input as code.
  • Search with strfind, which returns the starting positions of every match (here 2 and 4 in "banana").
  • Regular expressions are supported by regexp and regexprep. regexp(..., 'tokens') returns the captured groups of each match as a cell array; pairs{2}{:} takes the second match's groups, "y" and "7".

char arrays and MATLAB's string type

MATLAB also has a string type, created with the string function (since release R2016b) or with double quotes (since R2017a). A string holds a whole piece of text as one element, so an array of strings can hold texts of different lengths, and MATLAB added functions such as contains, strlength, join, pad and replace to go with it. Octave 11 implements none of these: double quotes create an ordinary char array, and string, contains, strlength and replace are undefined. If you write MATLAB code that might have to run in Octave, keep to char arrays and the classic functions shown here, which work on both char arrays and (in MATLAB) strings. startsWith, endsWith and strsplit are available in both.

Worked examplesH

Cell arrays

Definition— Cell array

A cell array is an array whose elements, called cells, can each hold any value. It is created with braces: {42, 'text', [1 2 3]}. Indexing with parentheses returns a smaller cell array; indexing with braces returns the contents of the cells.

matlab
cities = {'Lagos', 'Lima', 'Hanoi', 'Oslo'};
fprintf('%s %s %s\n', class(cities), class(cities(2)), class(cities{2}));

lens = cellfun(@numel, cities);
disp(lens)
shouted = cellfun(@upper, cities, 'UniformOutput', false);
fprintf('%s ', shouted{:});
fprintf('\n');

sorted = sort(cities);
fprintf('%s ', sorted{:});
fprintf('\n');
[tf, where] = ismember({'Oslo', 'Paris'}, cities);
disp([tf; where])

parts = strsplit('2026-11-19', '-');
disp(str2double(parts) + [0 1 0])
disp(strjoin(fliplr(parts), '/'))

mixed = {42, 'text', [1 2 3], {'nested'}, @sin};
for k = 1:numel(mixed)
  fprintf('%d: %s\n', k, class(mixed{k}));
end
text
cell cell char
   5   4   5   4
LAGOS LIMA HANOI OSLO 
Hanoi Lagos Lima Oslo 
   1   0
   4   0
   2026     12     19
19/11/2026
1: double
2: char
3: double
4: cell
5: function_handle
  • The first line is the most important distinction in this lesson: cities(2) is a 1-by-1 cell, while cities{2} is the char array inside it. Use () to select, reorder or delete cells; use {} to get at what is in them.
  • A cell array of char arrays (often called a cellstr) is the classic way to hold a list of texts of different lengths. sort, unique, ismember, strcmp, upper, strjoin and many more accept them directly.
  • cellfun applies a function to each cell. If every result is a scalar, it returns an ordinary array (lens); otherwise you must say 'UniformOutput', false and get a cell array back.
  • cities{:} with braces and a colon produces a comma-separated list: it is as if you had typed cities{1}, cities{2}, cities{3}, cities{4}. That is why fprintf('%s ', shouted{:}) prints every element. You will see this trick everywhere: passing a cell's contents as separate arguments, or collecting several outputs.
  • strsplit returns a cellstr, and str2double converts a whole cellstr to numbers at once.
Worked examplesH

Structs and struct arrays

Definition— Struct

A struct groups values under field names: station.name = 'Quito' creates the struct station (if needed) and its field name. Fields can hold any value, including other structs. A struct array is an array of structs that all have the same fields.

matlab
station.name = 'Quito';
station.elevation = 2850;
station.readings = [14.2 15.1 13.8];
fprintf('%s: %d m, mean %.1f C\n', station.name, station.elevation, mean(station.readings));

field = 'elevation';
disp(station.(field))
disp(strjoin(fieldnames(station)', ', '))
disp(isfield(station, 'country'))

stations = station;
stations(2) = struct('name', 'Mombasa', 'elevation', 50, 'readings', [27.5 28.1]);
stations(3) = struct('name', 'Ulaanbaatar', 'elevation', 1350, 'readings', [-21 -18.5 -19.2 -20]);
disp(size(stations))
elevations = [stations.elevation];
[~, order] = sort(elevations, 'descend');
for s = stations(order)
  fprintf('%-12s %5d m %6.1f C over %d readings\n', s.name, s.elevation, mean(s.readings), numel(s.readings));
end
meanTemps = arrayfun(@(s) mean(s.readings), stations);
disp(meanTemps)

surprise = struct('name', {'a', 'b'});
disp(size(surprise))
intended = struct('tags', {{'a', 'b'}});
disp(size(intended))
disp(class(intended.tags))
text
Quito: 2850 m, mean 14.4 C
2850
name, elevation, readings
0
   1   3
Quito         2850 m   14.4 C over 3 readings
Ulaanbaatar   1350 m  -19.7 C over 4 readings
Mombasa         50 m   27.8 C over 2 readings
   14.367   27.800  -19.675
   1   2
   1   1
cell

(The readings are made-up sample values; the elevations are approximate.)

  • Dynamic field names: station.(field) uses the value of field as the field name, so code can choose fields at run time, for example from a configuration file.
  • fieldnames lists the fields as a cellstr, and isfield tests for one.
  • Struct arrays hold one record per element. Each record may have arrays of different lengths in the same field, which a matrix could not do.
  • [stations.elevation] is the comma-separated-list trick again: stations.elevation expands to the three elevations as separate values, and the brackets concatenate them into a vector. With text fields, use braces instead: {stations.name} gives a cellstr of the names.
  • Sorting records by a field is two steps: sort the extracted values, keeping the permutation order, then index the struct array with it.
  • arrayfun over a struct array computes something per record.

The last lines show the classic struct trap. When you pass a cell array as a value to struct, MATLAB creates one struct per cell. struct('name', {'a', 'b'}) is therefore a 1-by-2 struct array, not one struct holding two names. To store a cell array in a field, wrap it in another pair of braces.

Worked examplesH

Maps and JSON

When you need to look values up by a text key, such as stock levels by product name, use containers.Map, which both programs provide. (Recent MATLAB versions also have a newer dictionary type, not available in Octave 11.)

matlab
stock = containers.Map();
stock('tea') = 12;
stock('rice') = 40;
stock('tea') = stock('tea') - 5;
disp(stock.Count)
disp(isKey(stock, 'coffee'))
items = keys(stock);
for i = 1:numel(items)
  fprintf('%s: %d\n', items{i}, stock(items{i}));
end

words = strsplit('the cat and the hat and the bat', ' ');
[unique_words, ~, idx] = unique(words);
counts = accumarray(idx(:), 1)';
for i = 1:numel(unique_words)
  fprintf('%s=%d ', unique_words{i}, counts(i));
end
fprintf('\n');

txt = jsonencode(struct('city', 'Quito', 'temps', [14.2 15.1], 'coastal', false));
disp(txt)
back = jsondecode('{"city": "Hanoi", "temps": [29.5, 30.1], "coastal": true}');
fprintf('%s %.1f %d\n', back.city, back.temps(2), back.coastal);
disp(size(back.temps))
text
2
0
rice: 40
tea: 7
and=2 bat=1 cat=1 hat=1 the=3 
{"city":"Quito","temps":[14.2,15.1],"coastal":false}
Hanoi 30.1 1
   2   1
  • A containers.Map is a handle object: unlike arrays and structs, copying it gives a second reference to the same map, so a function that receives a map can change it. keys returns the keys in sorted order.
  • The word count does not need a map at all. unique with three outputs returns the distinct words and, for every original word, the index of its distinct word; accumarray then adds 1 for each occurrence. This "unique then accumarray" pattern is the vectorised way to group and count, and you will use it again for data analysis.
  • jsonencode turns structs, arrays, cellstrs and logicals into JSON text, and jsondecode goes the other way, turning JSON objects into structs and arrays of numbers into column vectors (note the size 2-by-1). Both functions exist in MATLAB and in Octave since version 7, which makes JSON a convenient, portable format for configuration files and results.
ComputationC

Worked example: from raw text to records

Real data rarely arrive clean. Here are eight lines as a field logger might write them, with an extra space in one line, an unreadable value in another and a status message mixed in. The program turns them into records, converts the numbers, groups by station and writes a report, using nearly every tool in this lesson:

matlab
% Raw lines from three field loggers: date, station, temperature in C.
lines = {'2026-03-01 Quito 14.2'
         '2026-03-01 Mombasa 27.5'
         '2026-03-02   Quito 15.1'
         '2026-03-02 Mombasa n/a'
         '2026-03-02 Ulaanbaatar -21.0'
         '2026-03-03 Quito 13.8'
         'battery low'
         '2026-03-03 Mombasa 28.1'};

% 1. Parse: one struct of named tokens per line that matches.
pattern = '^(?<date>\d{4}-\d{2}-\d{2})\s+(?<station>\w+)\s+(?<temp>\S+)$';
parsed = regexp(lines, pattern, 'names');
matched = ~cellfun(@isempty, parsed);
fprintf('%d of %d lines matched; skipped: "%s"\n', nnz(matched), numel(lines), strjoin(lines(~matched)', '", "'));
records = [parsed{matched}];
fprintf('records is a %dx%d %s array; record 3 is %s, %s, %s\n', size(records), class(records), ...
        records(3).date, records(3).station, records(3).temp);

% 2. Convert: text to numbers, with NaN marking unreadable values.
temps = str2double({records.temp});
for r = records(isnan(temps))
  fprintf('unreadable temperature at %s on %s: "%s"\n', r.station, r.date, r.temp);
end

% 3. Group: one row per station, ignoring unreadable values.
[names, ~, g] = unique({records.station});
g = g(:);
temps = temps(:);
good = ~isnan(temps);
counts = accumarray(g(good), 1, [numel(names) 1]);
means = accumarray(g(good), temps(good), [numel(names) 1], @mean, NaN);

% 4. Report: a padded char matrix for people, JSON for programs.
rows = cell(numel(names) + 1, 1);
rows{1} = sprintf('%-12s %2s %8s', 'station', 'n', 'mean C');
for k = 1:numel(names)
  rows{k + 1} = sprintf('%-12s %2d %8.2f', names{k}, counts(k), means(k));
end
report = char(rows);
disp(report)
fprintf('the report is a %dx%d char matrix\n', size(report));

summary = struct('station', names, 'mean', num2cell(round(means' * 10) / 10));
disp(jsonencode(summary))
text
7 of 8 lines matched; skipped: "battery low"
records is a 1x7 struct array; record 3 is 2026-03-02, Quito, 15.1
unreadable temperature at Mombasa on 2026-03-02: "n/a"
station       n   mean C
Mombasa       2    27.80
Quito         3    14.37
Ulaanbaatar   1   -21.00
the report is a 4x24 char matrix
[{"station":"Mombasa","mean":27.8},{"station":"Quito","mean":14.4},{"station":"Ulaanbaatar","mean":-21}]

Step by step:

  1. Parse with a pattern, not by position. (?<date>...) is a named token. With the 'names' option, regexp returns a struct whose fields are the token names, and given a cell array of lines it returns a cell array with one result per line. A line that does not match gives an empty result, so cellfun(@isempty, ...) finds the lines to skip. The pattern also documents the expected format: \s+ accepts any run of spaces, and the anchors ^ and $ reject lines with anything extra. [parsed{matched}] uses a comma-separated list to concatenate the matching structs into one struct array. The ... at the end of a line continues a statement on the next.
  2. Convert once, mark failures. {records.temp} collects a text field from every record, and str2double converts them all, turning "n/a" into NaN rather than stopping. Looping over records(isnan(temps)) reports exactly the bad records.
  3. Group with unique and accumarray, as in the word count above, keeping only good values. The [numel(names) 1] argument fixes the size of the result, so a station whose readings were all bad would still get a row, with a count of 0; the last argument of the second call makes its mean NaN rather than accumarray's default fill value, 0, which would look like a real temperature.
  4. Report. char applied to a cellstr pads every text with spaces to the same length and stacks them into a char matrix, one line per row, which disp prints as a block. (Writing ['abc'; 'de'] fails, because the rows of a matrix must have equal lengths; char does the padding for you.) Finally, struct with cell-array values builds a struct array, one record per station: the "struct trap" from earlier, used on purpose. jsonencode turns it into a JSON array of objects that any other program can read.
ExplanationH

Choosing a container

With matrices, char arrays, cells, structs, struct arrays and maps all available, beginners often reach for the wrong one. A rough guide:

DataContainer
Numbers all of one kind, in a grida numeric matrix
A list of texts of different lengthsa cell array of char arrays
One record with named partsa struct
Many records with the same fieldsa struct array (or, in MATLAB, a table)
Lookup by text keycontainers.Map (or a struct with dynamic fields for simple cases)
Truly mixed data with no structurea cell array, as a last resort

Two pieces of practical advice. First, keep numbers in numeric arrays whenever you can, because that is where vectorisation works. A struct array with a readings field per record is fine, but a column of a thousand temperatures belongs in one double vector, not in a thousand cells. Second, MATLAB's table type, a column-oriented container with named, typed columns, is the standard tool for tabular data in MATLAB today, and much of MATLAB's data-analysis documentation is written around it. Octave does not implement table; in Octave, the usual substitutes are a struct of column vectors (one field per column) or a numeric matrix plus a cellstr of column names. Lesson 8 uses the former.

Common misconceptionsH

Common misconceptions

Misconception

"if name == 'yes' checks whether two texts are equal." It compares characters one by one, errors when the lengths differ, and is true only if every character matches. Use strcmp(name, 'yes').

Misconception

"c(2) gives me the second element of a cell array." It gives a 1-by-1 cell containing it. You need c{2} for the element itself. When a function complains that it received a cell, this is usually why.

Misconception

"struct('tags', {'a', 'b'}) makes a struct with a cell field." It makes a struct array with two elements. Wrap the cell in another set of braces to store it as a single field value.

Misconception

"Double quotes are just another way to write text." In MATLAB they create a string, a different type; in Octave a char array with escape sequences. Code that mixes the two behaves differently in each program.

Exercises

Exercises

1. Text, cell arrays and structs

Warm-upComputational

What does this print?

c = {7, 'seven', [7 7]};
fprintf('%s %s %d\n', class(c(2)), class(c{2}), numel(c{3}));

2. Text, cell arrays and structs

Warm-upHuman

reply holds whatever text a user typed. Which condition correctly tests whether it is exactly yes, in both MATLAB and Octave, whatever its length?

Choose one

3. Text, cell arrays and structs

CoreComputational

What does this display?

s = struct('id', {10, 20, 30});
disp(numel(s))

4. Text, cell arrays and structs

CoreComputational

What does this display?

s(1).v = 4;
s(2).v = 6;
s(3).v = 1;
disp(sum([s.v]) * numel(s))

5. Text, cell arrays and structs

CoreComputational

What does the first fprintf print? (%g prints a number in its shortest natural form, followed here by a space.)

x = str2double({'3.5', 'n/a', '1e2', ' 7 '});
fprintf('%g ', x);
fprintf('\n');

6. Text, cell arrays and structs

Warm-upComputational

What does this print?

parts = strsplit('red,green,blue', ',');
disp(strjoin(fliplr(parts), ' + '))

7. Text, cell arrays and structs

StretchComputational

What does this Octave script print?

1;
function bumpMap(m)
  m('n') = m('n') + 1;
end
function bumpStruct(s)
  s.n = s.n + 1;
end

m = containers.Map();
m('n') = 1;
s.n = 1;
bumpMap(m);
bumpStruct(s);
fprintf('%d %d\n', m('n'), s.n);

8. Text, cell arrays and structs

CoreComputational

What does this print?

[u, ~, k] = unique({'oak', 'ash', 'oak', 'elm', 'oak', 'ash'});
counts = accumarray(k(:), 1)';
fprintf('%s:%d ', u{1}, counts(1), u{end}, counts(end));
fprintf('\n');

Further reading and resources