在MATLAB中,我该如何将结构体数组保存到文本文件中,以便显示命令窗口中结构体数组显示的所有内容?
%assume that your struct array is named data
temp_table = struct2table(data);
writetable(temp_table,'data.csv')
现在你的结构数组已经存储在data.csv文件中。列名是结构体字段名,行则是结构体数组中不同的单个结构体。
首先,您需要定义文件格式。
如果您不关心文件格式,只是想在以后能够加载数据,请使用save
命令,例如:
save 'myfile.mat' structarr
将结构体数组structarr
存储在名为"file.mat"的二进制MAT文件中。要将其读回工作区,您可以使用load
函数:
load 'myfile.mat'
如果您想将结构体数组保存在文本文件中作为逗号分隔的值对,其中每个值对包含字段名和其值,您可以按照以下方式进行操作:
%// 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);
这个解决方案假定每个字段都包含一个标量值或字符串,但你可以根据需要进行扩展。
str = matlab.unittest.diagnostics.ConstraintDiagnostic.getDisplayableString(yourArray);
fid = fopen('myFile.txt', 'w');
fwrite(fid, str, '*char');
fclose(fid);