print a cell array as .txt in Matlab

不打扰是莪最后的温柔 提交于 2019-12-04 10:26:28

The following will work for your example:

C = cellarray.';
fid = fopen('file.dlm', 'wt');
fprintf(fid, '"%s"\t"%s"\t%g\n', C{:});
fclose(fid);

MATLAB reuses the formatting string until it runs out of inputs. In principle, you could construct the formatting string first:

fstr = '';
for ic = 1:size(cellarray,2)
   switch class(cellarray{1,ic})
       case 'char'
           fstr = [fstr '"%s"'];
       otherwise
           % Assume numeric
           fstr = [fstr '%g'];
   end
   if ic < size(cellarray,2), fstr = [fstr '\t']; else fstr = [fstr '\n']; end
end

Then

C = cellarray.';
fid = fopen('file.dlm', 'wt');
fprintf(fid, fstr, C{:});
fclose(fid);

I often use combination of DLMWRITE and XLSWRITE. DLMWRITE is used to make a text file, so XLSWRITE will not generate the file in Excel format, but will leave it as a text.

filename = 'file.txt';
dlmwrite(filename, 1)
xlswrite(filename, cellarray)

Note that on OS where COM is not available (like Linux) XLSWRITE write to text, so you don't need the call to DLMWRITE.


UPDATE

This method does not work anymore with the latest versions of MATLAB (since probably R2012b). xlswrite always writes to Excel-formatted file.

However, since R2013b MATLAB introduced TABLES, and WRITETABLE function works great if cell array can be converted to a table (check CELL2TABLE function).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!