Skip to content
Cell Arrays and Structs
step 1/5

Reading — step 1 of 5

Learn

~1 min readHeterogeneous Data

Regular arrays in Octave are homogeneous — all numbers, or all strings. Cell arrays hold mixed types.

c = {"Ada", 36, [1 2 3], {true, false}}

c{1}        % "Ada" — index with curly braces
c{3}(2)     % 2 — index into the inner array
c(1)        % {"Ada"} — round braces give a sub-cell
length(c)   % 4

The {} extracts the element. The () returns a cell sub-array.

Cell arrays in functions — pass mixed arguments:

args = {"hello", "world"};
result = strcat(args{:});      % expand to multiple arguments

The {:} syntax expands a cell into a comma-separated list — like Python's *args.

cellfun — apply f to each cell:

lengths = cellfun(@length, {"hi", "hello", "x"})    % [2 5 1]

Structs — named-field records:

person.name = "Ada";
person.age = 36;
person.skills = {"math", "engines"};

fieldnames(person)        % {"name", "age", "skills"}
person.skills{1}          % "math"

Struct arrays — array of structs:

people(1).name = "Ada";
people(1).age = 36;
people(2).name = "Bob";
people(2).age = 25;

[people.age]              % [36 25] — extract field across array

For most data analysis you'll use struct arrays for tabular records and cell arrays for ad-hoc heterogeneous data.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…