How Can I Save a Struct Array to a Text File?

65 views (last 30 days)
I have a struct array. Each field in the struct arrray is a column vector, and the column vectors are of unequal lengths.
s(1).t=[1;2];s(1).x=[10;20];s(2).t=[21;22;23];s(2).x=[100;101;102];
My goal is save the data in s to a text file with the elements of each field in s vertically concatenated. The file should look like this:
>> type file1.txt
t,x
1,10
2,20
21,100
22,101
23,102
I thought that struct2table followed by writetable might give me what I want. But, consistent with its doc page, struct2table doesn't do the vertical concatenation the way I hoped it would:
tbl=struct2table(s)
tbl =
2×2 table
t x
____________ ____________
[2×1 double] [2×1 double]
[3×1 double] [3×1 double]
At present my solution is as follows:
for ii=1:2,s(ii).t = s(ii).t.'; s(ii).x = s(ii).x.';end
snew.t=[s.t].'; snew.x=[s.x].';
tblnew=struct2table(snew)
tblnew =
5×2 table
t x
__ ___
1 10
2 20
21 100
22 101
23 102
And then I can witetable(tnew).
After I typed all that up, I did find a better way:
s(1).t=[1;2];s(1).x=[10;20];s(2).t=[21;22;23];s(2).x=[100;101;102];
C=arrayfun(@(x) struct2table(x),s,'UniformOutput',false);
vertcat(C{:})
ans =
5×2 table
t x
__ ___
1 10
2 20
21 100
22 101
23 102
These two lines aren't too bad, except for the need to create the intermediate variable C. Is there an easier and/or better way to write my original struct array to a text file? If it makes it any easier, I may not need the column headings in the text file.
Comment: According the doc in my release, the result of struct2table for a 1 x 2 struct array input is not defined. But, as shown, it worked fine and returned the same result as for a 2 x 1 struct array input..

Accepted Answer

Ameer Hamza
Ameer Hamza on 4 Oct 2020
You can directly create a matrix
M = cell2mat(struct2cell(s(:)).')
writematrix(M, 'filename.txt')

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!