在Matlab中将单元格数组打印为.txt

Mad*_*ddy 4 matlab printf text-files

我有一个单元格数组需要根据特定格式打印在.txt文件中.我已经尝试了一些在线帮助(包括matlab中心,dlmcell但即使这样也没有给我想要的答案.Delimiter是\ t.

cellarray = { ...
        'AAPL' '2/20/2011' 100.5 
        'MSFT' '2/15/2011' 43.4551
            } ;
Run Code Online (Sandbox Code Playgroud)

输出应该是.txt文件,格式如下:(使用制表符分隔符)

"AAPL"    "2/20/2011"    100.5
"MSFT"    "2/15/2011"    43.4551
Run Code Online (Sandbox Code Playgroud)

单元格最少有8000行,最多15000行.没有行会有空列.矢量化解决方案是否可行?应该感谢你的帮助.

Nzb*_*buu 7

以下内容适用于您的示例:

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

MATLAB重用格式化字符串,直到输出用完为止.原则上,您可以首先构造格式化字符串:

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
Run Code Online (Sandbox Code Playgroud)

然后

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