Search code examples
matlabcell-arraywritetofile

Matlab write cell array of numbers into file


I have a cell array like this:

cellarr{1}=[1 2 3];
cellarr{2}=[1 2 3 4 5 6];
...

Each cell is a vector of numbers with different length. I want to write this cell array into a text file so that i can read it later. The text file should look like this:

1 2 3
1 2 3 4 5 6

If I use dlmwrite('file.txt',cellarr,'\t') it puts all cells into one line. How do I put a new line character after writing a cell to the text file?

P/S: I could use fprintf with two for loops to get what I want. But is there a faster way to do that?


Solution

  • I was wondering why do you need two for loops?

    fid = fopen('file.txt', 'wt');
    for i = 1 : length(cellarr)
       fprintf(fid, '%d\t', cellarr{i});
       fprintf(fid,'\n');
    end
    fclose(fid)