Writing a structure to a txt file

20 views (last 30 days)
BC on 6 Mar 2021
Commented: BC on 6 Mar 2021
I have a structure which contains some parameters for a function:
F1Parameters.adaptedThresholdValue = 0.38;
F1Parameters.BWopenValue = 800;
F1Parameters.seDiskValue = 32;
I want to be able to write this to a text file in the following format, which keeps the structure name as the first column.
Function Parameter Value
F1_Parameters adaptedThresholdValue 0.38
F1_Parameters BWopenValue 800
F1_Parameters seDiskValue 32
To do this, I'm using the code below, but this seems like a very inefficient way to do it - am I missing an obvious way of just exporting the structure with the structure name as the first column?
% write F1 parameters to a txt file
table_F1Parameters = struct2table(F1Parameters); % convert F1 parameters to table
transposed_F1Parameters = rows2vars(table_F1Parameters); % transpose table
column_F1 = (repelem("F1_Parameters",height(transposed_F1Parameters)))'; % create new column to label F1, repeat name of structure
column_F1 = array2table(column_F1); % convert new column to table
final_F1_table = [column_F1,transposed_F1Parameters]; % concatenate column and table
final_F1_table.Properties.VariableNames = ["Function","Parameter","Value"]; % rename headers
writetable(final_F1_table,sprintf("%s",myFolderOutput,"Parameters"),"Delimiter","tab"); % write table to txt file

Accepted Answer

Mario Malic
Mario Malic on 6 Mar 2021
fieldnames function is useful in this case. There is maybe a better or/and simpler way to do this. However, there seems to be an issue which is weird, I am trying this in MATLAB Online. File is tab delimited in the first row correctly, but in others, delimiters between 2nd and 3rd column are 'space' characters.
t = table(repmat({'F1_Parameters'}, [height(fieldnames(F1Parameters)), 1]), fieldnames(F1Parameters), struct2cell(F1Parameters), ...
'VariableNames', {'Function', 'Parameter', 'Value'});
writetable(t, 'testtablefile.txt', 'Delimiter', 'tab');
Method with writecell
% Append the variable names for cells
data = [repmat({'F1_Parameters'}, [height(fieldnames(F1Parameters)), 1]), fieldnames(F1Parameters), struct2cell(F1Parameters)];
writecell(data, 'testfile.txt', 'Delimiter', 'tab');
  1 Comment
BC on 6 Mar 2021
Thank you, definitely simpler than my method. The tab delimiter is working fine for me :)

Sign in to comment.

More Answers (0)


Find more on Characters and Strings in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!