How do I convert a column of struct array to split into multiple columns in a table
7 次查看(过去 30 天)
显示 更早的评论
Hi,
I have a struct array and when I use struct2table to convert it to a table some of the data appears as 1x2 double or 2x2 double (see below).
I want to combine the name column and one other data column into a table.
I have tried this
for i = 1:18
C(i).Name = data3(i).Name;
C(i).TestData = data3(i).TestData;
end
Table4 = struct2table(C);
The name column is fine, but the confidence interval one displays as
>> disp(Table4)
TestData
____________
{2×3 double}
{2×2 double}
{2×2 double}
{2×2 double}
{2×2 double}
{2×2 double}
{2×2 double}
{2×2 double}
{2×2 double}
{2×2 double}
{2×1 double}
{2×3 double}
{2×2 double}
{2×2 double}
{2×2 double}
{2×2 double}
{2×2 double}
{2×1 double}
Is there a way to split the double up so that each array displays in a column in the table, for example:
Name Test Data1 TestData2 TestData3
2 个评论
Stephen23
2022-9-7
How does a 2x3 matrix correspond to the four columns of the table?
How does a 2x2 matrix correspond to the four columns of the table?
How does a 2x1 matrix correspond to the four columns of the table?
回答(1 个)
Geetla Sindhu
2022-9-7
You can try the following steps:
% Convert your cell arrays in TestData into arrays using cell2mat
t1 = varfun(@cell2mat, Table4, 'InputVariables', {'TestData'});
t1.Properties.VariableNames = {'TestData'};
% varfun modifies the names, change them back
% Split TestData into multiple columns
t1 = splitvars(t1, 'TestData', 'NewVariableNames', {'TestData1', 'TestData2', 'TestData3'});
% Finally expand Name column
t1.Name = repelem(Table4.Name, [3,2,1]);
You can look at the following example for better understanding:
T = 3×2 table
data Name
{3×3 double} "Chang"
{2×3 double} "Brown"
{[79 75 74]} "Ruiz"
>>t1 = varfun(@cell2mat, T, 'InputVariables',{'data'});
>>t1.Properties.VariableNames = {'data'};
>>t1 = splitvars(t1, 'data', 'NewVariableNames', {'data1', 'data2', 'data3'});
>> t1.Name = repelem(T.Name,[3,2,1]);
>> t1
6×4 table
data1 data2 data3 Name
79 75 73 "Chang"
180 178 177.5 "Chang"
220 210 205 "Chang"
79 75 73 "Brown"
180 178 177.5 "Brown"
79 75 74 "Ruiz"
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!