table2structofarray​s( inTable )

版本 1.0.0.0 (1.5 KB) 作者: Todd Leonhardt
Function to convert a table to a struct of arrays
37.0 次下载
更新时间 2016/5/21

查看许可证

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

引用格式

Todd Leonhardt (2024). table2structofarrays( inTable ) (https://www.mathworks.com/matlabcentral/fileexchange/57197-table2structofarrays-intable), MATLAB Central File Exchange. 检索时间: .

MATLAB 版本兼容性
创建方式 R2016a
兼容任何版本
平台兼容性
Windows macOS Linux
类别
Help CenterMATLAB Answers 中查找有关 Tables 的更多信息

Community Treasure Hunt

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

Start Hunting!
版本 已发布 发行说明
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.