How to save a structure array to a text file

后端 未结 3 1772
走了就别回头了
走了就别回头了 2020-12-18 03:07

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?

相关标签:
3条回答
  • 2020-12-18 03:47

    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

    0 讨论(0)
  • 2020-12-18 03:52

    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);
    
    0 讨论(0)
  • 2020-12-18 04:00

    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.

    0 讨论(0)
提交回复
热议问题