File Exchange

image thumbnail

table2structofarray​s( inTable )

version (1.48 KB) by Todd Leonhardt
Function to convert a table to a struct of arrays


Updated 21 May 2016

View License

You cannot pass a MATLAB Table data type to a MEX function (or at least you cannot extract that Table within the MEX function using the mxArray API). So you need to convert that table to something else. There are built-in functions for converting to a cell array or an array of structs. But converting to a cell array loses the variable names and converting to an array of structs has horrible performance implications. So I wrote this function to convert a table to a struct of arrays where each variable in the table becomes a field in the struct and the variable names are the field names.
function [ outStruct ] = table2structofarrays( inTable )
%TABLE2STRUCTOFARRAYS Convert a table to a struct of arrays.
% Usage: outStruct = TABLE2STRUCTOFARRAYS( inTable )
% Convert a table with M rows and N variables to a struct with N fields,
% each of which contains a 1-dimensional array of length M and where the
% field names in the struct are the same as the variable names in the
% table.
% NOTE: There ia a built-in function TABLE2STRUCT which converts a table to
% an array of structs. However, there are HUGE performance advantages of
% a struct of arrays over an array of structs.

% Make sure the input really is a table
if ~isa(inTable, 'table')
error('Error. Input to function %s must be a table, not a %s', mfilename, class(inTable))

% Create an empty struct with no fields
outStruct = struct;

% If the table has explicitly defined row names, then add a field for these
if ~isempty(inTable.Properties.RowNames)
outStruct = setfield(outStruct, 'RowNames', inTable.Properties.RowNames)

% Iterate through all of the variables in the table
for varNum=1:width(inTable)
% Get the variable name as a cell array with 1 element
varNameCell = inTable.Properties.VariableNames(varNum);

% Extract the variable name as a string
varName = varNameCell{1};

% Add a new field to the struct containing the data for this variable
outStruct = setfield(outStruct, varName, inTable.(varNum));


Cite As

Todd Leonhardt (2021). table2structofarrays( inTable ) (, MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2016a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!