How to export a struct to flat file?

19 次查看(过去 30 天)
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.
  9 个评论
Peter Erhardt
Peter Erhardt 2019-4-23
I'm working on getting a few rows out and de-identifying it.
Peter Erhardt
Peter Erhardt 2019-4-23
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.

请先登录,再进行评论。

采纳的回答

Guillaume
Guillaume 2019-4-23
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 个评论
dpb
dpb 2019-4-23
编辑:dpb 2019-4-24
Precisely, or variations thereof...yours keeping the table is good; I'd written another for the numeric values alone along the lines of
tM=struct2table(MCI1);
A=table2array(tM(:,4:end));
L=cellfun(@length,A(:,1));
A=cell2mat([arrayfun(@(i,L)kron(i,ones(L,1)),[1:size(A,1)].',L,'uni',0)]);
Agree, however, this whole idea seems a large step backwards rather than forward...

请先登录,再进行评论。

更多回答(0 个)

Community Treasure Hunt

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

Start Hunting!

Translated by