Search code examples
arraysstringmatlabexport-to-csv

Saving a string array to CSV


I have a 25194081x2 matrix of strings called s1. Below an outlook of how the data looks like.

enter image description here

I am trying to save this matrix to csv. I tried the code below but for some reason it saves the first column of the vector twice (side by side) instead of the two columns.

What am I doing wrong?

fileID= fopen('data.csv', 'w') ;
 fprintf(fileID, '%s,%s\n', [s1(:,1) s1(:,2)]);
 fclose(fileID)

Solution

  • Dont merge the columns to a string array like you do now, but provide them as separate arguments, and loop over the rows of s1:

    fileID= fopen('data.csv', 'w') ;
    for k = 1:size(s1,1)
        fprintf(fileID, '%s,%s\n', s1(k,1), s1(k,2));
    end
    fclose(fileID)
    

    Or, if you're using >R2019a, you can use writematrix:

    writematrix(s1, 'data.csv');