merging two text files and generate 1000 copies of the new text (or dat) file

조회 수: 1 (최근 30일)
Hi, I need to generate a 1000 text (or dat) files to be fed into another software. I have two text files (aa.txt and bb.txt) and an equation that generates random numbers. The produced text (or dat) file is to be comprised of aa.txt , the randomly generated numbers and finally the contents of bb.txt.

채택된 답변

Sergey Kasyanov
Sergey Kasyanov 2018년 4월 6일
편집: Sergey Kasyanov 2018년 4월 6일
You should to read help for sprintf and fprintf for operating with this code.
Also I used dirty solution for new string line for Windows: char([13,10]) because matlabs '\n' is not working on my computer. You may use '\n'.
Files={'aa.txt','bb.txt'};
Fids=[fopen(Files{1},'r'),fopen(Files{2},'r')];
DataBefore=textscan(Fids(1),'%s');
DataAfter=textscan(Fids(2),'%s');
fclose(Fids(1));
fclose(Fids(2));
for i=1:10
%There you can name output files
FID=fopen(sprintf('output_%i.txt',i),'w');
for j=1:length(DataBefore{1})
fprintf(FID,['%s',char([13,10])],DataBefore{1}{j});
end
RandomNumbers=rand(1e3,1);
for j=1:length(RandomNumbers)
%There you should define number printing type and length
fprintf(FID,['%5.2f',char([13,10])],RandomNumbers(j));
end
for j=1:length(DataAfter{1})
fprintf(FID,['%s',char([13,10])],DataAfter{1}{j});
end
fclose(FID);
end
  댓글 수: 3
Sergey Kasyanov
Sergey Kasyanov 2018년 4월 6일
I made a mistake. Sorry. Below is better version.
DataBefore=fileread('aa.txt');
DataAfter=fileread('bb.txt');
for i=1:10
%There you can name output files
FID=fopen(sprintf('output_%i.txt',i),'w');
fprintf(FID,'%s',DataBefore);
RandomNumbers=rand(1e3,1);
for j=1:length(RandomNumbers)
%There you should define number printing type and length
fprintf(FID,['%5.2f',char([13,10])],RandomNumbers(j));
end
fprintf(FID,'%s',DataAfter);
fclose(FID);
end
Mohammed Hadi
Mohammed Hadi 2018년 4월 6일
Yes, dear Sergey, it is fully working now
Thank you very much indeed

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Language Support에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by