Search code examples
matlabfile-iocsvcell-array

Outputing cell array to CSV file ( MATLAB )


I've created a m x n cell array using cell(m,n), and filled each of the cells with arbitrary strings.

How do I output the cell array as a CSV file, where each cell in the array is a cell in the CSV 'spreadsheet'.

I've tried using cell2CSV, but I get errors ...

Error in ==> cell2csv at 71
    fprintf(datei, '%s', var);

Caused by:

Error using ==> dlmwrite at 114
The input cell array cannot be converted to a matrix.

Any guidance will be well received :)


Solution

  • Here is a somewhat vectorized solution:

    %# lets create a cellarray filled with random strings
    C = cell(10,5);
    chars = char(97:122);
    for i=1:numel(C)
        C{i} = chars(ceil(numel(chars).*rand(1,randi(10))));
    end
    
    %# build cellarray of lines, values are comma-separated
    [m n] = size(C);
    CC = cell(m,n+n-1);
    CC(:,1:2:end) = C;
    CC(:,2:2:end,:) = {','};
    CC = arrayfun(@(i) [CC{i,:}], 1:m, 'UniformOutput',false)';     %'
    
    %# write lines to file
    fid = fopen('output.csv','wt');
    fprintf(fid, '%s\n',CC{:});
    fclose(fid);
    

    The strings:

    C = 
        'rdkhshx'       'egxpnpvnfl'    'qnwcxcndo'    'gubkafae'      'yvsejeaisq'
        'kmsvpoils'     'zqssj'         't'            'ge'            'lhntto'    
        'sarlldvig'     'oeoslv'        'xznhcnptc'    'px'            'qdnjcdfr'  
        'jook'          'jlkutlsy'      'neyplyr'      'fmjngbleay'    'sganh'     
        'nrys'          'sckplbfv'      'vnorj'        'ztars'         'xkarvzblpr'
        'vdbce'         'w'             'pwk'          'ofufjxw'       'qsjpdbzh'  
        'haoc'          'r'             'lh'           'ipxxp'         'zefiyk'    
        'qw'            'fodrpb'        'vkkjd'        'wlxa'          'dkj'       
        'ozonilmbxb'    'd'             'clg'          'seieik'        'lc'        
        'vkpvx'         'l'             'ldm'          'bohgge'        'aouglob'   
    

    The resulting CSV file:

    rdkhshx,egxpnpvnfl,qnwcxcndo,gubkafae,yvsejeaisq
    kmsvpoils,zqssj,t,ge,lhntto
    sarlldvig,oeoslv,xznhcnptc,px,qdnjcdfr
    jook,jlkutlsy,neyplyr,fmjngbleay,sganh
    nrys,sckplbfv,vnorj,ztars,xkarvzblpr
    vdbce,w,pwk,ofufjxw,qsjpdbzh
    haoc,r,lh,ipxxp,zefiyk
    qw,fodrpb,vkkjd,wlxa,dkj
    ozonilmbxb,d,clg,seieik,lc
    vkpvx,l,ldm,bohgge,aouglob