Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Reading and Replace lines in input data for many lines

1 ビュー (過去 30 日間)
Ivan Mich
Ivan Mich 2020 年 4 月 12 日
終了済み: MATLAB Answer Bot 2021 年 8 月 20 日
Hello,
I have a problem with a code.
Imagine that I have File3.txt, File2.txt and one .exe file (lets call it my.exe). File3.txt has my data, File2.txt is the input of my.exe(input that is needed in order to execute my.exe).
I would like from file3 to take only one line and put in a specific line of the file2(input). After putting this line in file2 I can run my exe file. The problem is that File 3 obtain many lines. I want to use o for loop in order to run my .exe file for all the lines separately of file3 (I mean I would like to take the first line of 2nd and 3rd column from file 3, put this line to file2, run my.exe file and take my results. After that I would like to take the second line of 2nd and 3rd column from file 3, put this line to file2, run my.exe file and take my results. After all this repeatability I would like to the last line of 2nd and 3rd column of file 3 put this line to file2, run my.exe file and take my results.)
I have to mention that I want after each repeatability the name of input file (File2.txt) does not change, inspite of the different content.
%for
% for j= 1: size{lines_to_replace_with,1}
%
% line_to_replace_withnew = sprintf('%g\t%g',lines_to_replace_with(j));
% end
t3 = readtable('Files3.txt', 'readvariablenames', true);
nrow = size(t3,1);
lines2 = regexp(fileread('File2.txt'), '\r?\n', 'split') .';
for K = 1 : nrow
line_to_replace_with = sprintf('%g\t%g',t3{K,2:3});
replaced_lines = [lines2(1:2); line_to_replace_with; lines2(4:end)];
newfilename = sprintf('newfile%d.txt', K);
fid = fopen(newfilename, 'wt');
fprintf(fid, '%s\n', replaced_lines{:});
fclose(fid);
end
system('my.exe <File2.txt')
Could you please help me?
  3 件のコメント
Rik
Rik 2020 年 4 月 13 日
What code would you write for one line from files3? Then it should be relatively easy to extend it.
t3=function_to_read_to_cell;
data=cell(size(t3))
for n=1:numel(t3)
function_to_write_file2(t3{n});
system('my.exe <File2.txt')
data(n)=function_to_read_back_results;
end

回答 (1 件)

Stijn Haenen
Stijn Haenen 2020 年 4 月 13 日
What about creating a new txt file in every loop and overwriting the existing file2.txt instead of replacing lines?
  2 件のコメント
Stijn Haenen
Stijn Haenen 2020 年 4 月 13 日
Here is an example:
text_example='test';
number_example=10;
txt_file=fopen(sprintf('File2.txt'),'wt');
fprintf(txt_file,'%s\n','test0'); %writing text, \n means new rule
fprintf(txt_file,'%s\n',text_example);
fprintf(txt_file,'%g\n',3); %writing number
fprintf(txt_file,'%g\n',number_example);
fclose(txt_file);

Community Treasure Hunt

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

Start Hunting!

Translated by