如何在Matlab中合并两个文本文件并复制生成的文件?

时间:2018-04-06 14:44:15

标签: matlab text

我需要生成一些文本(或数据)文件,以便输入另一个软件。我有两个文本文件(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');

1 个答案:

答案 0 :(得分:1)

这基本上应该产生你想要的东西:

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.txtbb.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