在Matlab中将单元格数组打印为.txt [英] print a cell array as .txt in Matlab
问题描述
我有一个单元格数组,需要根据特定格式将其打印为.txt文件.我已经尝试了一些在线帮助(包括matlab Central dlmcell
,但即使这样也不能给我想要的答案.定界符为\ t.
I have a cell array that needs to be printed in a .txt file according to a specific format. I have tried some of the online help (including matlab central dlmcell
but even that is not giving me the desired answer. Delimiter is \t.
cellarray = { ...
'AAPL' '2/20/2011' 100.5
'MSFT' '2/15/2011' 43.4551
} ;
输出应为以下格式的.txt文件:(使用制表符分隔符)
The output should be in a .txt file with the following format: (using tab delimiter)
"AAPL" "2/20/2011" 100.5
"MSFT" "2/15/2011" 43.4551
该单元格将最少包含8000行,最多15000.没有行将具有空列.向量化解决方案可能吗?感谢您的帮助.
The cell will have minimum of 8000 rows and a maximum of 15000. No rows would have empty columns. Is a vectorized solution possible? Shall appreciate your help.
推荐答案
以下内容适用于您的示例:
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重复使用格式化字符串,直到用尽输入为止.原则上,您可以先构造格式字符串:
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
然后
C = cellarray.';
fid = fopen('file.dlm', 'wt');
fprintf(fid, fstr, C{:});
fclose(fid);
这篇关于在Matlab中将单元格数组打印为.txt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!