3

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.

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

The first bullet was a typo on my end which I corrected in the question. Thanks for the help.

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.