Search code examples
matlabcsvcell-array

How to write a cell array to csv in Matlab while keeping the structure of the cell array for the strings


I am trying to write out a cell aray to a csv file in Matlab. data{1,:} is equal to headers and data{2,:} has the data (2x23). The data in the cell array has a mixture of strings and numbers. One of the cells in the array has a very long string/comment and when I try to write it out to a csv, the string gets broken up into a number of pieces and printed out over 3 cells in the csv file. This pushes all of the other information out of sync with it's associated header. This is what I'm currently trying:

 fid = fopen('test.csv', 'w') ;
fprintf(fid, '%s,\t', csvdata{1,1:end}) ;
fprintf(fid,'\n,%f, %f, %f,%f, %f, %s,%s, %f, %f,%s, %f, %s,%s, %f, %s,%s, %s, %s,%s, %s,%s,%s,%s',csvdata{2,:});
fclose all

Solution

  • You should enclose your strings with double quotes (") to ensure that the commas within the strings are treated as literal commas rather that delimiters

    fprintf(fid,'\n,%f, %f, %f,%f, %f, "%s","%s", %f, %f,"%s", %f, "%s","%s", %f, "%s","%s", "%s", "%s","%s", "%s","%s","%s","%s"',csvdata{2,:});