How to save an array of structure to a text file

In MATLAB, how do I save a structure array to a text file so that it displays everything that the structure array shows in the command window?

+4
source share
4 answers

You must first determine the format for your file.

Saving to a MATLAB workspace file (. MAT)

If you don’t need a format and just want to load the data later, use save , for example:

 save 'myfile.mat' structarr 

Saves an array struct structarr in a binary MAT file named "file.mat". To read it back to the workspace, you can use load :

 load 'myfile.mat' 

Saving as Comma Separated Values ​​(.CSV)

If you want to save your array of structures in a text file as pairs of values ​​separated by commas, where each pair contains the field name and its value, you can do something in these lines:

 %// Extract field data fields = repmat(fieldnames(structarr), numel(structarr), 1); values = struct2cell(structarr); %// Convert all numerical values to strings idx = cellfun(@isnumeric, values); values(idx) = cellfun(@num2str, values(idx), 'UniformOutput', 0); %// Combine field names and values in the same array C = {fields{:}; values{:}}; %// Write fields to CSV file fid = fopen('myfile.csv', 'wt'); fmt_str = repmat('%s,', 1, size(C, 2)); fprintf(fid, [fmt_str(1:end - 1), '\n'], C{:}); fclose(fid); 

This solution assumes that each field contains a scalar value or string, but you can expand it as you see fit.

+4
source

I know this thread is outdated, but I hope it helps someone anyway:

I think this is a shorter solution (with the limitation that each field of the structure can contain scalar, arrays or strings):

 %assume that your struct array is named data temp_table = struct2table(data); writetable(temp_table,'data.csv') 

Now your array of structures is stored in the data.csv file. Column names are the names of the structure fields, and the rows are different single structures of your structural array.

+4
source

To convert any data type to a character vector, as shown in the MATLAB command window, use the function

 str = matlab.unittest.diagnostics.ConstraintDiagnostic.getDisplayableString(yourArray); 

Then you can write the contents to a file

 fid = fopen('myFile.txt', 'w'); fwrite(fid, str, '*char'); fclose(fid); 
0
source

Use fprintf

fprintf (fileID, formatSpec, A1, ..., An) applies formatSpec to all elements of arrays A1, ... An in column order and writes the data to a text file. fprintf uses the encoding scheme specified in the call to Eorep.

-2
source

All Articles