How to export struct saved in workspace to text file

Hi, I have a struct with some fields inside. I want to be able to export the struct (or at least 2 of the fields inside) to a text file. Any help would be appreciated. Thanks

6 Comments

What output format do you need ?
Have you considered Json encode?
As you can tell, I haven't used nor have knowledge on json. As long as I can get a .txt file at the end with the fields in a readable format within the text file I really dont care how I get it to work

see https://www.mathworks.com/help/matlab/ref/jsonencode.html#mw_69b38ba2-26d1-4025-a426-d1bf8ca939a7

Great thank you, definetely something I need to look into and expand my knowlegde on

Sign in to comment.

 Accepted Answer

Convert to table and then wrtie to text file:
% Example 1: convert and write to table
S.Str = 'I Love MATLAB'
S = struct with fields:
Str: 'I Love MATLAB'
S.Date = datetime("now")
S = struct with fields:
Str: 'I Love MATLAB' Date: 01-Aug-2022 14:21:48
Stb = struct2table(S)
Stb = 1×2 table
Str Date _____________ ____________________ I Love MATLAB 01-Aug-2022 14:21:48
writetable(Stb, "Stb.txt")
Edit:
% Example 2: using jsonencode and fprintf
clear
S.A1 = [9.9, 9900];
S.A2 = [8.8, 7.7 ; ...
8800, 7700];
S = jsonencode(S, "PrettyPrint", true)
S =
'{ "A1": [ 9.9, 9900 ], "A2": [ [ 8.8, 7.7 ], [ 8800, 7700 ] ] }'
  • Export to text file
I do not know about your struct, so I'm skipping formatSpec.
NB: fprintf has an option called formatSpec that you may need to set as first argument to fprintf.
fileID = fopen('myS.txt','w');
nbytes = fprintf(fileID,S) ;
fclose(fileID);
Hope this helps

5 Comments

Thank you for your response, I got the following as an error, please could you help
Error using struct2table (line 97)
Input structure is a scalar, but its fields have different numbers of rows. If you intended to create a table with
one row, set 'AsArray' to true.
You can solve this by setting AsArray to true :
Stb = struct2table(S, "AsArray",true)
Thank you that works, but the text file isnt very usable. Is there a way to get the specific fields within the struct? I have tried but this doesnt seem to work
myTable = struct2table(data.var, "AsArray", true);
Great thank you, so much nicer now. Really appreicated all the help

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2021a

Community Treasure Hunt

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

Start Hunting!