How to save a structure array to a text file

荒凉一梦 提交于 2019-11-28 01:13:16

问题


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:


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




回答2:


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.




回答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);


来源:https://stackoverflow.com/questions/15460600/how-to-save-a-structure-array-to-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!