Skip to content

Instantly share code, notes, and snippets.

@ahebrank
Created September 26, 2014 15:18
Show Gist options
  • Save ahebrank/60f1266b9d87b27c7755 to your computer and use it in GitHub Desktop.
Save ahebrank/60f1266b9d87b27c7755 to your computer and use it in GitHub Desktop.
Write out csv file with header
function csvhwrite(fn, data, hdr)
% function csvhwrite(fn, data, hdr)
% write a csv file with cell array hdr (cols in data must match length of hdr)
if isempty(fn)
fn = spm_input('Filename: ', '+1', 's');
end
if size(data,2)~=length(hdr)
error('Header length does not match data');
end
fout = fopen(fn,'w');
for i=1:length(hdr)
if i==length(hdr)
fprintf(fout, '%s', hdr{i});
else
fprintf(fout, '%s,', hdr{i});
end
end
fprintf(fout, '\n');
for r=1:size(data,1)
for c=1:size(data,2)
if c==size(data,2)
% don't print the final comma
fprintf(fout, '%0.4g', data(r,c));
else
fprintf(fout, '%0.4g,', data(r,c));
end
end
fprintf(fout, '\n');
end
fclose(fout);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment