MATLAB: Fprintf one data per cell from text to csv

delimitersformattingfprintfoutput

Hi all, I've written the following code to help me copy the third column from multiple text files to one csv spreadsheet in the following format: header is 'Trails', followed by third column of each text file displayed horizontally per row (thus no \n).
fidO = fopen('pvtsort.csv','wt');
d = dir('*txt');
for i = 1:length(d)
fid = fopen(d(i).name, 'r'); % open all input txt files, no array
values = textscan(fid,'%*s%*s%s','HeaderLines',4, 'Delimiter','\t');% read only the 3rd column
fprintf(fidO,'%s\t','Trails');
for j = 1:length(values{1,1})
pvt = values{1,1}
fprintf(fidO,'%s\t',pvt{j}); %note "the curlies" to dereference cellstr to char
end
fprintf(fidO,'\r\n')
fid = fclose(fid);
end
fidO = fclose(fidO)
Well the output looks fine when I open the csv in matlab, with one data point occupying one cell, one column of data per row with header "Trails" in front. However, when I open my output spreadsheet 'pvtsort.csv' directly outside matlab, it looks funny. All the data points from one column are crammed into a cell instead of separate cells like how the csv was displayed in matlab (as if the '\t' didn't work). I played around with several delimiters like \v, \r,combinations of these with '\t', but could not for the life of me figure out why data wasn't displayed properly when opening csv outside matlab. Pointers appreciated.

Best Answer

Just guessing here since I don’t have your files and so can’t run your code, but since .csv indicates comma-separated variables, perhaps:
fprintf(fidO,'%s, ','Trails');
and
fprintf(fidO,'%s, ',pvt{j}); %note "the curlies" to dereference cellstr to char
could work.