Search code examples
matlabfile-iotext-filescell-array

How can I append a cell array to a .txt file?


I previously queried about including matrices and strings in a .txt file. I now need to append cells to it. From my prior question:

str = 'This is the matrix: ';
mat1 = [23 46; 56 67];
fName = 'output.txt';
fid = fopen(fName, 'w');
if fid >= 0
    fprintf(fid, '%s\n', str);
    fclose(fid);
end
dlmwrite(fName, mat1, '-append', 'newline', 'pc', 'delimiter', '\t');

Now I want to append a string: 'The removed identifiers are' and then this cell array below it:

'ABC' [10011] [2]
'DEF' [10023] [1] 

Some relevant links:

http://www.mathworks.com/help/techdoc/ref/fileformats.html, http://www.mathworks.com/support/solutions/en/data/1-1CCMDO/index.html?solution=1-1CCMDO


Solution

  • Unfortunately, you can't use functions like DLMWRITE or CSVWRITE for writing cell arrays of data. However, to get the output you want you can still use a single call to FPRINTF, but you will have to specify the format of all the entries in a row of your cell array. Building on my answer to your previous question, you would add these additional lines:

    str = 'The removed identifiers are: ';   %# Your new string
    cMat = {'ABC' 10011 2; 'DEF' 10023 1};   %# Your cell array
    fid = fopen(fName,'a');                  %# Open the file for appending
    fprintf(fid,'%s\r\n',str);               %# Print the string
    cMat = cMat.';                          %'# Transpose cMat
    fprintf(fid,'%s\t%d\t%d\r\n',cMat{:});   %# Print the cell data
    fclose(fid);                             %# Close the file
    

    And the new file contents (including the old example) will look like this:

    This is the matrix: 
    23  46
    56  67
    The removed identifiers are: 
    ABC 10011   2
    DEF 10023   1