Search code examples
matlabcsvcell-array

How to write multiple .csv files from cell array in matlab


I have a cell array. I want to write each element of the cell into a .csv file and also specifically name the file along the way.

This is my attempt:

for i=1:length(somecell)
     doublecell{i}=double(somecell{i});   
end

for j=1:length(doublecell)
    z=doublecell{j};
    csvwrite('matrix_%i.csv',z,j)
end

I hope what I'm attempting to do is clear even though it's wrong.


Solution

  • You can shorten (and correct) your code as:

    for i = 1:length(somecell)
        doubleVal = double(somecell{i});
        csvwrite(sprintf('matrix_%i.csv', i), doubleVal);
    end
    

    You don't have to store the double values in an intermediate cell array, as you can produce the elements while you write the CSV files.

    There were actually two problems with your code:

    • The line z=doublecell(j) produces a cell as indexing a cell-array with parenthesis produces a cell. You would need the numeric value instead, so here the curly bracket indexing would be correct: z = doublecell{j}.

    • The line csvwrite('matrix_%i.csv',z,j) is incorrect. You would need sprintf to create the filename (see example).