Cell Arrays

A cell array holds values of different types and sizes in one container: c = {'VCU', 2.41, [1 2 3]}.

Concept

A cell array holds values of different types and sizes in one container: c = {'VCU', 2.41, [1 2 3]}.

c{2} (curly braces) The contents of cell 2 c(2) (parentheses) A 1×1 cell containing it c{end + 1} = x

A comma-separated list of all contents (for function arguments)

Typical uses: lists of texts ({'VCU', 'BMS'}), heterogeneous records, variable-length data per channel, varargin/varargout.

Functions: cell(m, n) preallocates, iscell, iscellstr, cellfun, cell2mat (when contents are compatible), num2cell, strjoin, sort and ismember for cell arrays of text.

Why It Matters

Real data is rarely a neat matrix: file names, ECU names, per-test results of varying length. Cell arrays hold them together.

Syntax

names = {'VCU', 'BMS', 'GW'};
first = names{1};                     % 'VCU'
n = cellfun(@numel, names);           % [3 3 2]
[tf, loc] = ismember('GW', names);

Example

14.1 Creating, indexing and processing cell arrays

c = {'VCU', 2.41, [1 2 3]; true, {'nested'}, @sin}
fprintf('class(c{1,2}) = %s, class(c(1,2)) = %s\n', class(c{1, 2}), class(c(1, 2)))
ecus = {'VCU', 'BMS', 'GW'};
ecus{end + 1} = 'ABS';
fprintf('%d ECUs: %s\n', numel(ecus), strjoin(ecus, ', '))
fprintf('ismember(''BMS'', ecus) = %d, find(strcmp(ecus, ''GW'')) = %d\n', ismember('BMS', ecus), find(strcmp(ecus, 'GW')))
[sorted, idx] = sort(ecus);
fprintf('sorted: %s (from positions %s)\n', strjoin(sorted, ', '), mat2str(idx))
readings = {[12.6 12.4], [11.9], [13.1 13.0 12.9]};
counts = cellfun(@numel, readings);
means = cellfun(@mean, readings);
fprintf('readings per ECU: %s, means: %s\n', mat2str(counts), mat2str(means, 4))
iscellstr(ecus)

Expected Result

c{1,2} gave the double inside the cell, c(1,2) a 1×1 cell. Readings of different lengths per ECU were summarized with cellfun.

c =
{
  [1,1] = VCU
  [2,1] = 1
  [1,2] = 2.4100
  [2,2] =
  {
    [1,1] = nested
  }

  [1,3] =

     1   2   3

  [2,3] = @sin
}

class(c{1,2}) = double, class(c(1,2)) = cell
4 ECUs: VCU, BMS, GW, ABS
ismember('BMS', ecus) = 1, find(strcmp(ecus, 'GW')) = 3
sorted: ABS, BMS, GW, VCU (from positions [4 2 3 1])
readings per ECU: [2 1 3], means: [12.5 11.9 13]
ans = 1

Common Mistakes

Using () when you need the contents ({}), or vice versa.

Trying arithmetic on a cell (c + 1 is an error).

cell2mat on contents of incompatible sizes.

Using cell arrays for purely numeric data (slower and clumsier than a matrix).

Best Practices

Use cells for heterogeneous or ragged data, matrices for numeric grids, structs for named fields.

Preallocate with cell(1, n).

Use cellfun(..., 'UniformOutput', false) for non-scalar results.

Interview Relevance

Medium: "cell array vs matrix?", "c{1} vs c(1)?", "how do you store texts of different lengths?".

Practice Questions

Store three test names and their pass/fail results in a 3×2 cell array and print a table.

Find the longest name in a cell array of names.

Convert {1, 2, 3} to a numeric vector.

Pass the contents of a cell array as separate arguments to fprintf using c{:}.

Quick Quiz

Q1. (Multiple choice) Which returns the contents of the first cell? A) c(1) B) c{1} C) c[1] D) c.1 Answer: B.

Q2. (Predict the output) class(c(1,2)) where c{1,2} = 2.41.

Answer: cell (verified).

Q3. (True/False) A cell array can contain another cell array.

Answer: True (verified: {'nested'} inside c).

Q4. (Find the bug) names = {'VCU', 'BMS'}; if names(1) == 'VCU', ... end

Answer: names(1) is a cell; use strcmp(names{1}, 'VCU') (or strcmp(names, 'VCU') for all).

Coding Challenge

Given tests = {'VIN read', 'DTC clear', 'Flash VCU'} and passed = [true false true], build and print a report line per test and the names of failed tests joined by commas.

tests = {'VIN read', 'DTC clear', 'Flash VCU'};
passed = [true false true];
labels = {'FAIL', 'PASS'};
for k = 1:numel(tests)
    fprintf('%-10s %s\n', tests{k}, labels{passed(k) + 1})
end
fprintf('failed: %s\n', strjoin(tests(~passed), ', '))