gpt4 book ai didi

matlab - 在 Matlab 中将元胞数组打印为 .txt

转载 作者:太空宇宙 更新时间:2023-11-03 19:51:03 24 4
gpt4 key购买 nike

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

cellarray = { ...
'AAPL' '2/20/2011' 100.5
'MSFT' '2/15/2011' 43.4551
} ;

输出应在具有以下格式的 .txt 文件中:(使用制表符分隔符)

"AAPL"    "2/20/2011"    100.5
"MSFT" "2/15/2011" 43.4551

单元格最少有 8000 行,最多有 15000 行。没有行会有空列。是否可以使用矢量化解决方案?将感谢您的帮助。

最佳答案

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

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

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

然后

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

关于matlab - 在 Matlab 中将元胞数组打印为 .txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8565617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com