MATLAB - write cell array to csv file

13,370

Example:

%# cellarray
C = {
    'abc' [1]  [131]
    'def' []   []
    'gh'  [13] [999]
};

%# write line-by-line
fid = fopen('file.csv','wt');
for i=1:size(C,1)
    fprintf(fid, '%s,%d,%d\n', C{i,:});
end
fclose(fid);
Share:
13,370
Trup
Author by

Trup

Updated on June 04, 2022

Comments

  • Trup
    Trup almost 2 years

    I have a cell array that has both characters and numbers as values. What is the simplest way to output it in a csv file, row by row, maintaining the structure of the cell array? For example, if the cell array is

    [abc] [1] [131]
    [def] [] []
    [gh] [13] [999]
    

    I want the file to look like

    abc,1,131
    def,,
    gh,13,999
    
  • Trup
    Trup over 12 years
    Should this file already exist or I create it this way? I am getting ??? Error using ==> fprintf Invalid file identifier. Use fopen to generate a valid file identifier. Error in ==> parseTickData at 134 fprintf(fd, '%s,%f,%d%f%d%f%d\n', C{i,:});
  • Amro
    Amro over 12 years
    @Trup: it should create a new file if it didn't already exist, and overwrite it if it did.. Also can you show us what a row in your actual cellarray looks like?