Write cell array to text file

Post date: Nov 17, 2012 5:43:30 PM

We can write a cell array to text file in MATLAB. Example code is shown below.

% Prepare cell array to write mycell = {{'box#1:','cat','dog'}; {'box#2:','A','B','C','D'}; {}; {'box#4:'}; {}; {'box#11:','you'}} % output filename outfile = 'myTextFile'; filename = [outfile,'.txt']; % initialize/open the file fid = fopen(filename, 'w'); % write each cell to the text file [nrows,ncols]= size(mycell); for row=1:nrows fprintf(fid, 'label#%d :',row); for col=1:length(mycell{row}) fprintf(fid, '%s ', mycell{row}{col}); end fprintf(fid, '\n'); end % close file when done fclose(fid);

The output text file "myTextFile.txt" would like like:

label#1 :box#1: cat dog
label#2 :box#2: A B C D
label#3 :
label#4 :box#4:
label#5 :
label#6 :box#11: you

See also:

  • writing cell array to text file [url]
  • write to text file [url]