Skip to content

vlt.data.flattenstruct2table

 FLATTENSTRUCT2TABLE Flattens a structure to a table, preserving nested struct array data.

    T = flattenstruct2table(S)
    T = flattenstruct2table(S, ABBREV)

  ## Description

  This function converts a structure or structure array `S` into a MATLAB `table`
  `T`. Nested field names are concatenated with a '.' to form the table's
  variable names (e.g., a field `Sub.Value` becomes a variable named 'Sub.Value').

  This version is an **optimized replacement** for an older implementation. It
  is specifically designed to replicate the legacy behavior for **nested struct
  arrays**. When a field contains a struct array (with more than one element),
  its data is *not* unrolled into multiple rows. Instead, the values from each
  sub-field are collected into a cell array and placed within a **single cell**
  of the output table. This ensures backward compatibility.

  This implementation is also highly optimized for speed and avoids the common
  MATLAB performance bottleneck of growing a table inside a loop.

  ## Input Arguments

    S - The input structure or structure array to flatten.

    ABBREV - (Optional) An Nx1 cell array used to shorten long variable
             names. Each cell must contain a 1x2 cell, such as
             `{'string_to_replace', 'replacement'}`.

  ## Output Arguments

    T - The resulting flattened `table`.

  ## Example

    % Create a structure with a nested struct array
    Sub = struct('X', {10, 20}, 'Y', {'a', 'b'}); % A 1x2 struct array
    S = struct('A', Sub, 'C', 3);

    % Flatten the structure
    T = flattenstruct2table(S)

    % The output will be a 1x3 table:
    %
    %      A_X        A_Y      C
    %    ________    _______    ___
    %    {[10 20]}    {'a' 'b'}    3
    %
    % Note how the data from the S.A.X and S.A.Y fields is nested
    % within single cells, rather than creating two separate rows.