Saving a struct to a text file exactly how it appears in command window
조회 수: 36 (최근 30일)
이전 댓글 표시
Hello, I have a struct called settings. I am wanting to save it to a text file in an easily readable format. Im trying to avoid manually using fprintf and have used the table apporach as:
path='F:\settings.txt';
settings = struct; %Create structure called settings
settings.exposure_ms=num2str(app.ExposuremsEditField.Value);
settings.gain=app.GainDropDown.Value;
settings.BlueLaser_mA=num2str(app.mABlueEditField.Value);
settings.GreenLaser_mA=num2str(app.mAGreenEditField.Value);
settings.date= datestr(now,'dd-mmm-yyyy HH-MM-SS'); %get current dateTime
settings
T=struct2table(settings)
class(T)
writetable(T, path,'Delimiter','tab')
However, this gives the field names as "headings" in the table and as they don't align up in a normal text file is quite difficult to read.
I am wanting to get the text file more in the format of the struc itself (i.e. settings), i.e. rows are field names, then on the same row the field value
I have played with other snippeds I've googled but none are letting me do what I want to do.
% M = cell2mat(struct2cell(settings(:)).')
% writematrix(M, path);
or
% T2= rows2vars(T)
% T.Properties
% Tc=table2cell(T)
% Tt = cell2table(Tc','RowNames',T.Properties.VariableNames,'VariableNames',T.Properties.DimensionNames)
채택된 답변
Les Beckham
2023년 5월 24일
Here is one approach.
path='F:\settings.txt';
settings = struct; %Create structure called settings
% settings.exposure_ms=num2str(app.ExposuremsEditField.Value);
settings.exposure_ms = 200; % << test value
% settings.gain=app.GainDropDown.Value;
settings.gain = 0; % << test value
% settings.BlueLaser_mA=num2str(app.mABlueEditField.Value);
settings.BlueLaser_mA = 300; % << test value
% settings.GreenLaser_mA=num2str(app.mAGreenEditField.Value);
settings.BlueLaser_mA = 290; % << test value
settings.date= datestr(now,'dd-mmm-yyyy HH-MM-SS'); %get current dateTime
settings
% T=struct2table(settings)
% class(T)
% writetable(T, path,'Delimiter','tab')
str = formattedDisplayText(settings);
writelines(str, 'settings.txt');
system('cat settings.txt');
댓글 수: 2
Les Beckham
2023년 5월 24일
편집: Les Beckham
2023년 5월 24일
The system command is just to display the contents of the text file that was written with the writelines command.
Steven Lord's comment above is a good one. Consider changing the name of your structure.
Also (even more importantly), don't name a variable "path" as that is a crucial keyword in Matlab. Call it "filePath" or anything else you want, just not "path".
If this answer solved your issue, please consider accepting it by clicking "Accept this Answer". Thanks.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Text Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!