Effacer les filtres
Effacer les filtres

How to make writetable write sub structures or tables

16 vues (au cours des 30 derniers jours)
Scott Tatum
Scott Tatum le 1 Nov 2018
With the following code:
bob = struct()
bob.joe = 1
bob.sam = '4'
bob.bill = [6:10]
bob.jim = struct('a',1,'b','q')
writetable(struct2table(bob))
I get the following output
joe,sam,bill_1,bill_2,bill_3,bill_4,bill_5,jim
1,4,6,7,8,9,10,
So the structure entry for 'jim' is just blank.
If I turn jim into a table
bob.jim = struct2table(bob.jim)
writetable(struct2table(bob))
The output now has the _1 and _2 for jim, but they are blank
joe,sam,bill_1,bill_2,bill_3,bill_4,bill_5,jim_1,jim_2
1,4,6,7,8,9,10,,
So how do I get writetable to deal with this? Preferably I would want the header to come out
joe,sam,bill_1,bill_2,bill_3,bill_4,bill_5,jim.a,jim.b
1 ,4 ,6 ,7 , 8 ,9 ,10 ,1 ,q
Also, if I am not writing to a spreadsheet, I would liek the ability to not expand arrays, so it would look like
joe,sam, bill, jim.a,jim.b
1 ,4 ,[6,7,8,9,10] ,1 ,q

Réponse acceptée

Himanshu
Himanshu le 6 Nov 2018
Hello Scott
As of MATLAB R2018b, "writetable" is not supported for nested tables. However, you can achieve something similar using the following workaround:
1. Create a file transformStruct.m with following contents
% Function to transform column with structure entries.
% It takes in a structure array and return two column
% arrays, one for each field of the structure
function [a b] = transformStruct(stArr)
a=[];
b={};
for i=1:length(stArr)
a(i) = stArr(i).a;
b{i} = stArr(i).b;
end
a=a';
b=b';
end
2. A file transformArr.m with following contents
% Function to transform column with array entries.
% It takes in a double array and returns a cell array of strings
function out = transformArr(arr)
out = {};
for i=1:size(arr,1)
out{i} = mat2str(arr(i,:));
end
out=out';
end
3. Finally a file main_script.m with contents
% create structure data with 3 rows
bob = struct();
bob.joe = [1; 2; 3];
bob.sam = ['4'; '5'; '6'];
bob.bill = [[6:10]; [11:15]; [16:20]];
bob.jim = [struct('a',1,'b','q'); struct('a',2,'b','r'); struct('a',3,'b','s')];
% create table from structure data
joe = bob.joe;
sam = bob.sam;
% transform the column bill to a cell array, so it
% does not split into separate columns
bill = transformArr(bob.bill);
% transform the column jim into two separate columns, one
% for each field
[jim_a jim_b] = transformStruct(bob.jim);
T = table(joe, sam, bill, jim_a, jim_b);
% write table to file
writetable(T)
Place all three files in a directory, and run the file main_script.m

Plus de réponses (0)

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Produits


Version

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by