我需要生成许多文本(或dat)文件,以供导入其他软件。我有两个文本文件(aa.txt和bb.txt)和一个生成随机数的方程式。
产生的文本(或.dat)文件由三部分组成:
1- aa.txt的内容。2-随机生成的数字。3- bb.txt的内容。
这些文件的内容是:
aa.txt->
first file ,,, first line
First file ,,, second line
1234.1234
bb.txt->
second file ,,, first line
second file ,,, second line
6789.6789
我编写了以下代码,但它只会产生一个包含第一个源文件(aa.txt)内容的文件。为什么我只能得到1个文件?为什么变量A没有写在生成的文件中?
NOF =3; % start with a goal to produce 3 files (small scale)
for ii = 1:NOF
ffid= fopen ('aa.txt','r'); % open the first source file (aa.txt), the idntifier is ffid
df = fopen (['file' sprintf('%d',ii) '.txt'], 'a'); % open a new (destination) file the identifier is df
line=fgets (ffid); % Read line from first source file
while ischar (line)
fprintf ('%s\n',line);
line =fgets (ffid);
fprintf (df , line); % write the newly-read line from first file to the destination file
end
fclose (ffid); % closing the first source file
A=randn(2,2); % this is just a randonly generated value for checking purposes and will be replaced later with a many sets of equations
save (['file' sprintf('%d',ii) '.txt'],'A', '-append');
sfid=fopen ('bb.txt','r'); % open the second source file, the idntifier is sfid
line2=fgets (sfid); % Read line from source file
while ischar (line2)
fprintf ('%s\n',line2);
line2 =fgets (sfid);
fprintf (df , line2);
end
fclose (sfid); % closing the first source file
end
fclose (df);
fclose('all');
这基本上应该产生您想要的东西:
for ii = 1:3
% Create the output file...
fid_out = fopen(['file' num2str(ii) '.txt'],'w');
% Read the whole content of the first file into the output file...
fid_aa = fopen('aa.txt','r');
while (~feof(fid_aa))
fprintf(fid_out,'%s\n',fgetl(fid_aa));
end
fclose(fid_aa);
% Generate the random matrix and write it to the output file...
random = cellstr(num2str(randn(2)));
for jj = 1:numel(random)
fprintf(fid_out,'%s\n',random{jj});
end
% Read the whole content of the second file into the output file...
fid_bb = fopen('bb.txt','r');
while (~feof(fid_bb))
fprintf(fid_out,'%s\n',fgetl(fid_bb));
end
fclose(fid_bb);
% Finalize the output file...
fclose(fid_out);
end
例如,给定aa.txt
具有以下内容的文件:
A - Line 1
A - Line 2
A - Line 3
以及bb.txt
具有以下内容的文件:
B - Line 1
B - Line 2
B - Line 3
输出文件将显示以下结构:
A - Line 1
A - Line 2
A - Line 3
0.18323 0.94922
-1.0298 0.30706
B - Line 1
B - Line 2
B - Line 3
为了优化的缘故,因为I / O是非常昂贵的,我建议你阅读的内容aa.txt
,并bb.txt
只有一次外产生的输出文件,并保存其内容为单元格阵列循环。方法如下:
fid = fopen('file.txt','r');
data = cell(0);
while (~feof(fid))
data{end+1} = fgetl(fid);
end
在产生输出文件的循环内部,然后可以迭代单元格数组内容以打印它们:
for jj = 1:numel(data)
fprintf(fid_out,'%s\n',data{jj});
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句