问题描述
请考虑以下内容:
DateTime = {'2007-01-01 00:00';'2007-02-01 00:00';'2007-03-01 00:00'};
Headers = {'Datetime','Data'};
Dat = [100,200,300];
Data = [DateTime,num2cell(Dat')];
Final = [Headers;Data];
如何将最终"中的数据写入制表符分隔的文本文件中.我知道当变量仅由数字输入组成但如何解决此问题时,如何使用fopen,fprintf等.我已经尝试过:
How would I write the data in 'Final' into a tab delimited text file. I know how to use fopen, fprintf and so on when the variable is composed of solely numerical inputs but am struggling to solve this problem. I have tried:
fid = fopen('C:\Documents\test.txt','wt');
fprintf(fid,'%s\t%s\n',Final{:});
fclose(fid);
但是,这不会生成与Matlab中生成的格式相同的文本文件.该问题如何解决?
However, this does not generate a text file that is in the same format as that generated in matlab. How can this problem be solved?
推荐答案
此解决方案提供了我认为您需要的内容;我希望有用的一些评论在旁边
This solution gives what I think you need; some remarks which I hope to be useful are on side
DateTime = {'2007-01-01 00:00';'2007-02-01 00:00';'2007-03-01 00:00'};
Headers = {'Datetime','Data'};
Dat = [100,200,300];
% // In the way you used fprintf it expects just strings ('%s\t%s\n'),
% // therefore Data should be composed exclusively by them.
% // Numbers are converted to strings by using num2str
% // by using cellfun we iteratively convert every element of num2cell(Dat')
% // in strings, obtaining a cell
Data = [DateTime,cellfun(@num2str, num2cell(Dat'), 'UniformOutput' , false )];
Final = [Headers;Data];
fid = fopen('test.txt','wt');
% // this iterates fprintf on the cell rows, giving you the output
cellfun(@(x,y) fprintf(fid,'%s\t%s\n',x,y),Final(:,1),Final(:,2));
fclose(fid);
结果
Datetime Data
2007-01-01 00:00 100
2007-02-01 00:00 200
2007-03-01 00:00 300
(来自评论),在N列单元格的一般情况下,您可以简单地进行for循环,例如
(from comments) in the general case of a N-columns cell, you can simply go for a for loop, e.g.
for i = 1 : size(Final,1)
fprintf(fid,'%s ', Final{i,:} );
fprintf(fid,'\n');
end
(结果相同,但不取决于列数).
(same result, but not depending on the number of columns).
这篇关于将组合的字符串和数字输入的单元格数组写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!