Writing a structure to a txt file

4 次查看(过去 30 天)
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

采纳的回答

Mario Malic
Mario Malic 2021-3-6
Hello,
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 个评论
BC
BC 2021-3-6
Thank you, definitely simpler than my method. The tab delimiter is working fine for me :)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by