How to save a structure array to a text file

2019-01-25 21:12发布

问题:

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

回答1:

You have to define a format for your file first.

Saving to a MATLAB workspace file (.MAT)

If you don't care about the format, and simply want to be able to load the data at a later time, use save, for example:

save 'myfile.mat' structarr

That stores struct array structarr in a binary MAT file named "file.mat". To read it back into your workspace you can use load:

load 'myfile.mat'

Saving as comma-separated values (.CSV)

If you want to save your struct array in a text file as comma-separated value pairs, where each pair contains the field name and its value, you can something along 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 a string, but you can extend it as you see fit, of course.



回答2:

I know this thread is old but I hope it's still going to help someone:

I think this is an shorter solution (with the constraint that each struct field 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 struct array is stored in the data.csv file. The column names are the field names of a struct and the rows are the different single-structs of your struct-array



回答3:

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

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

You can then write the contents to a file

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


回答4:

Use fprintf

fprintf(fileID,formatSpec,A1,...,An) applies the 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 fopen.