1

我想知道如何在输出文件 *.txt 中编写包含所有字段名和相应值的完整结构。例如

allvariables=

names='raw.txt'
date= = '**/**/2013'
User = Mr/Mrs *
timeProcessing = 20
numberIterations = 1000;

应该写在 output.txt 之前显示的所有信息。

这只是一个例子,但我的结构有 50 个字段名的长度,所以我会很感激任何建议!

4

1 回答 1

4

这是您可以使用的东西:

 %// Extract field data
fields = fieldnames(allvariables);
values = struct2cell(allvariables);

%// Optional: add enclosing apostrophes around string values
idx = cellfun(@ischar, values); 
values(idx) = cellfun(@(x){['''', x, '''']}, values(idx));

%// Convert numerical values to strings
idx = cellfun(@isnumeric, values); 
values(idx) = cellfun(@num2str, values(idx), 'UniformOutput', false);

%// Convert cell arrays of strings to comma-delimited strings
idx = cellfun(@iscellstr, values);
stringify_cellstr = @(x){['{' sprintf('''%s'', ', x{1:end - 1}) ...
   sprintf('''%s''', x{end}) '}']};
values(idx) = cellfun(stringify_cellstr, values(idx));

%// Convert cell array of numbers to strings
idx = cellfun(@iscell, values);
isnumber = @(x)isnumeric(x) && isscalar(x);
idx_num = cellfun(@(x)all(arrayfun(@(k)isnumber(x{k}),1:numel(x))), values(idx));
idx(idx) = idx_num;
stringify_cellnum = @(x){['{' sprintf('%d, ' x{1:end - 1}) num2str(x{end}) '}']};
values(idx) = cellfun(stringify_cellnum, values(idx));

%// Combine field names and values in the same array
C = {fields{:}; values{:}};

%// Write fields to text file
fid = fopen('output.txt', 'wt');
fprintf(fid, repmat('%s = %s\n', 1, size(C, 2)), C{:});
fclose(fid);

这个解决方案本质上是这个解决方案的一个变。请注意,它假定每个字段都包含一个标量值或字符串,但当然可以扩展它以处理其他类型。

编辑:添加了对存储字符串元胞数组和数字元胞数组的字段的处理。

于 2013-08-13T09:15:10.103 回答