Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a structure array to a text file

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?

like image 829
asdfqwer Avatar asked Mar 17 '13 12:03

asdfqwer


People also ask

How do I save a cell array as a text file in Matlab?

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.

How do you convert an array into a structure?

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.

How do I open a Matlab file?

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.


2 Answers

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

like image 157
v.tralala Avatar answered Oct 07 '22 16:10

v.tralala


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.

like image 21
Eitan T Avatar answered Oct 07 '22 14:10

Eitan T