04 Data Structures (Cells, Structs & Strings)

Overview: Heterogeneous Containers

While standard matrices only hold uniform numerical data, MATLAB features three dynamic types to store text and heterogeneous fields: Character/String Arrays, Cell Arrays, and Structures.


1. Text Representations: Character Arrays vs. Strings

MATLAB has two different formats for handling text:

  • Character Arrays (Legacy): Enclosed in single quotes: c = 'Hello'.
    • Mechanics: Stored as a row vector of characters.
    • Limitation: Concatenating different-length words vertically requires padding spaces so that row lengths match: char('one', 'three').
  • String Objects (Modern): Enclosed in double quotes: s = "Hello".
    • Mechanics: Stored as a single string object. Arrays of strings can contain elements of differing lengths without padding.

2. Cell Arrays: Container vs. Content Indexing

A Cell Array is a heterogeneous array whose elements can contain data of any type and size (matrices, characters, structures, other cells).

myCell = {'one', 42, [1 2; 3 4]};

The Indexing Difference: () vs. {}

This is a critical distinction in MATLAB cell manipulation:

  • Cell Indexing (): Returns a cell container containing the data.
    • myCell(1) returns a 1x1 cell containing 'one'.
  • Content Indexing {}: Returns the actual data payload wrapped inside the cell.
    • myCell{1} returns the character array 'one' directly.
Cell Array: [ Cell 1 ] ----> [ Cell 2 ]
                 |               |
                 v               v
myCell(1) =  {'one'}      myCell{1} = 'one' (payload)

3. Structures (struct)

Structures are key-value records with named fields.

Creation Syntax:

  • Dynamic Assignment: Fields are created on-the-fly using dot notation:
    A.b = {'one', 'two'};
    A.c = [1 2];
  • Structural Generator:
    • Syntax: S = struct(field1, value1, field2, value2, ...)
    • Description: Constructs a structure array with the specified fields and values.

💻 Conceptual Code Demonstration

% 1. Create a Cell Array
C = {'Text', [1 2 3], struct('key', 'val')};
 
% 2. Retrieve cell elements
cellWrapper = C(2); % Type: cell array containing [1 2 3]
innerData = C{2};   % Type: double array [1 2 3]
 
fprintf('Data class from {} indexing: %s\n', class(innerData));
fprintf('Data class from () indexing: %s\n', class(cellWrapper));
 
% 3. Dynamic structure assignment
device.name = "Sensor_A";
device.readings = [12.2, 13.5, 12.9];
device.status.active = true;
 
% Accessing structure fields
fprintf('Device: %s (Active: %d)\n', device.name, device.status.active);