table2structofarray​s( inTable )

Function to convert a table to a struct of arrays
38 Descargas
Actualizado 21 may 2016

Ver licencia

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))
end

% 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)
end

% 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));
end

end

Citar como

Todd Leonhardt (2026). table2structofarrays( inTable ) (https://es.mathworks.com/matlabcentral/fileexchange/57197-table2structofarrays-intable), MATLAB Central File Exchange. Recuperado .

Compatibilidad con la versión de MATLAB
Se creó con R2016a
Compatible con cualquier versión
Compatibilidad con las plataformas
Windows macOS Linux
Categorías
Más información sobre Tables en Help Center y MATLAB Answers.
Versión Publicado Notas de la versión
1.0.0.0

Just trying to format description a little better.
Moved insertion of Row Names to the end so that the variable number is the same as the field number.

Added code to description.