Writing a structure to a txt file

11 ビュー (過去 30 日間)
BC
BC 2021 年 3 月 6 日
コメント済み: BC 2021 年 3 月 6 日
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 Center および File ExchangeData Type Conversion についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by