MATLAB Answers


How to export a struct to flat file?

Asked by Peter Erhardt on 23 Apr 2019
Latest activity Edited by dpb
on 24 Apr 2019 at 1:04
First off, I have no background in MATLAB at all. I was given some .MAT files at work that I need to open and export to any flat file to be imported into another program. This is the only source of data, no opportunity to get it elsewhere or reformat it better (which I've seen suggested a few times in my research so far).
Here are a few example rows of data I have from 1 file. There are more columns of data, but the formatting got messed up. This file has 1500+ rows in it.
Each file has a slightly different set of columns, but pretty similar.
uniqueid id header var1 var2 var3 var4
'Unique ID 1' 1 9x1 cell 1045x1 double 1045x1 double 1045x1 double 1045x1 double
'Unique ID 2' 2 9x1 cell 1208x1 double 1208x1 double 1208x1 double 1208x1 double
'Unique ID 3' 3 9x1 cell 1365x1 double 1365x1 double 1365x1 double 1365x1 double
I'd like to get this into excel/csv/txt in 1 worksheet, with the 1045 rows for Unique ID 1, followed by the 1208 rows for Unique ID 2, followed by the 1365 rows for Unique ID 3, etc. Unique ID 1 and ID would just be repeated. Header I dont really need (they're column heading for the other variables?) var1, 2, 3, etc is what I really need parsed out.
I'd appreciate any code to get this exported to csv, txt, excel. Trying to learn the syntax is just not realistic for me given that we aren't using this software anymore.
I'm messing around with struct2table, xlswrite, writetable but really don't know what I'm doing so please be specific in any response.


on 23 Apr 2019 at 21:25
Ayup, that's why we need to see the .mat file to know what really might be pretty trivial, might not be, but how to know without knowing? :)
I'm working on getting a few rows out and de-identifying it.
Ok attached is the first 4 rows.
My hope is to end up with 1 file with 1045 rows + 1208 rows + 1365 rows + 1220 rows.
'pid' and 'subjind' would be repeated for their respective rows.
'header' I don't need.
'rtime' through 'subphase' would have the underlying double values split out.

Sign in to comment.

1 Answer

Answer by Guillaume
on 23 Apr 2019 at 23:07
 Accepted Answer

fnames = fieldnames(MCI1);
c = struct2cell(MCI1)';
heights = cellfun(@numel, c(:, 4));
t = [cell2table(repelem(c(:, [1 2]), heights, 1), 'VariableNames', fnames(1:2)), ...
array2table(cell2mat(c(:, 4:end)), 'VariableNames', fnames(4:end))];
writetable(t, 'somefile.xlsx');

  1 Comment

on 23 Apr 2019 at 23:51
Precisely, or variations thereof...yours keeping the table is good; I'd written another for the numeric values alone along the lines of
Agree, however, this whole idea seems a large step backwards rather than forward...

Sign in to comment.