csvwrite_with_headers.m (1941B)
1 % This function functions like the build in MATLAB function csvwrite but 2 % allows a row of headers to be easily inserted 3 % 4 % known limitations 5 % The same limitation that apply to the data structure that exist with 6 % csvwrite apply in this function, notably: 7 % m must not be a cell array 8 % 9 % Inputs 10 % 11 % filename - Output filename 12 % m - array of data 13 % headers - a cell array of strings containing the column headers. 14 % The length must be the same as the number of columns in m. 15 % fmt - 'precision' e.g. fmt=6 or fmt='%10.6f' 16 % r - row offset of the data (optional parameter) 17 % c - column offset of the data (optional parameter) 18 % 19 % 20 % Outputs 21 % None 22 function csvwrite_with_headers(filename,m,headers,fmt) 23 24 %% initial checks on the inputs 25 if ~ischar(filename) 26 error('FILENAME must be a string'); 27 end 28 29 % the r and c inputs are optional and need to be filled in if they are 30 % missing 31 r=0; 32 c=0; 33 34 % if nargin < 4 35 % r = 0; 36 % end 37 % if nargin < 5 38 % c = 0; 39 % end 40 41 if ~iscellstr(headers) 42 error('Header must be cell array of strings') 43 end 44 45 46 if length(headers) ~= size(m,2) 47 error('number of header entries must match the number of columns in the data') 48 end 49 50 %% write the header string to the file 51 52 %turn the headers into a single comma seperated string if it is a cell 53 %array, 54 header_string = headers{1}; 55 for i = 2:length(headers) 56 header_string = [header_string,',',headers{i}]; 57 end 58 %if the data has an offset shifting it right then blank commas must 59 %be inserted to match 60 if r>0 61 for i=1:r 62 header_string = [',',header_string]; 63 end 64 end 65 66 %write the string to a file 67 fid = fopen(filename,'w'); 68 fprintf(fid,'%s\r\n',header_string); 69 fclose(fid); 70 71 %% write the append the data to the file 72 73 % 74 % Call dlmwrite with a comma as the delimiter 75 % 76 dlmwrite(filename, m,'-append','delimiter',',','roffset', r,'coffset',c,'precision',fmt);