Writing a structure to a txt file

조회 수: 4 (최근 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 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