matlab - Write field name and value form structures to a file -


i wondering how can write full structure in output file *.txt fieldnames , respectives values. example

allvariables=  names='raw.txt' date= = '**/**/2013' user = mr/mrs * timeprocessing = 20 numberiterations = 1000; 

should written in output.txt information displayed before.

this example structure has length of 50 fieldnames, appreciate suggestion!

here's can use:

 %// 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 strings idx = cellfun(@isnumeric, values);  values(idx) = cellfun(@num2str, values(idx), 'uniformoutput', false);  %// convert cell arrays of strings 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 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 , values in same array c = {fields{:}; values{:}};  %// write fields text file fid = fopen('output.txt', 'wt'); fprintf(fid, repmat('%s = %s\n', 1, size(c, 2)), c{:}); fclose(fid); 

this solution variant of this one. note assumes each field contains scalar value or string, can extended handle other types, of course.

edit: added handling fields storing cell arrays of strings , cell arrays of numbers.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -