0001 function mrg_struct_to_csv(in, outfile)
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019
0020
0021
0022
0023
0024
0025
0026
0027
0028
0029 if ~isstruct(in)
0030 error('Input must be a structure')
0031 end
0032
0033 if ~ischar(outfile)
0034 error('Outfile must be a charater string')
0035 end
0036
0037 names = fieldnames(in);
0038 ncol = length(names);
0039
0040 lengths = ones(1,length(names),'int32');
0041 for n = 1:length(names)
0042 lengths(1,n) = length(in.(names{n}));
0043 end
0044
0045 if~(all(lengths==lengths(1)))
0046 error('All variables in the input structure must have the same length')
0047 end
0048
0049 nrow = unique(lengths);
0050
0051 fid = fopen(outfile, 'w');
0052
0053 for n = 1:length(names)-1
0054 fprintf(fid, '%s,', names{n});
0055 end
0056 fprintf(fid, '%s\n', names{length(names)});
0057
0058 for n = 1:nrow
0059
0060 for m = 1:length(names)-1
0061 val = in.(names{m})(n);
0062 if iscell(val)
0063 if isnumeric(val{:})
0064 fprintf(fid, '%f,', val{:});
0065 elseif ischar(val{:})
0066
0067 fprintf(fid, '"%s",', val{:});
0068 else
0069 error('Cannot handle a cell array which does not evaluate to either a number or a character')
0070 end
0071 elseif isnumeric(val)
0072 fprintf(fid, '%f,', val(:));
0073 else
0074 error('Cannot handle something that contains things other than cell or numeric arrays')
0075 end
0076 end
0077
0078 val = in.(names{length(names)})(n);
0079 if iscell(val)
0080 if isnumeric(val{:})
0081 fprintf(fid, '%f\n', val{:});
0082 elseif ischar(val{:})
0083 fprintf(fid, '%s\n', val{:});
0084 else
0085 error('Cannot handle a cell array which does not evaluate to either a number or a character')
0086 end
0087 elseif isnumeric(val)
0088 fprintf(fid, '%f\n', val(:));
0089 else
0090 error('Cannot handle something that contains things other than cell or numeric arrays')
0091 end
0092
0093
0094 end
0095
0096 fclose(fid);
0097
0098 end