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?
You can export a cell array from MATLAB® workspace into a text file in one of these ways: Use the writecell function to export the cell array to a text file. Use fprintf to export the cell array by specifying the format of the output data.
C = struct2cell( S ) converts a structure into a cell array. The cell array C contains values copied from the fields of S . The struct2cell function does not return field names. To return the field names in a cell array, use the fieldnames function.
On the Home tab, in the File section, click Open , and then select a file to open. You also can double-click the file in the Current Folder browser.
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
You have to define a format for your file first.
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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With