0

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

1 Answer 1

2

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,:});
Sign up to request clarification or add additional context in comments.

2 Comments

wow! so simple. How did I not know that! What's interesting is that if I put these double quotes for all the %s cells and some of them are empty, they write out the quote marks to the csv file?
@new2matlab yes that's the expected behavior. the "'s are literal quotes that are inserted into your string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.