필터 지우기
필터 지우기

Changing values(parameteres) in input text file at a certain line

조회 수: 1 (최근 30일)
MATErial,1
SOLId
PLANe STRAin
ELAStic ISOTropic 1000.0 0.25
! Blank termination record
COORdinates
1 0 0.0 0.0
2 0 4.0 0.0
3 0 10.0 0.0
4 0 0.0 4.5
5 0 5.5 5.5
6 0 10.0 5.0
7 0 0.0 10.0
8 0 4.2 10.0
9 0 10.0 10.0
! Blank termination record
ELEMents
1 1 1 1 2 5 4
2 1 1 2 3 6 5............................
The text file looks like this. I want to change the fourth line last two parameters 1000.0 and 0.25 to user defined input parameters and run the system command to execute the input text file in external program. Any help could you greatly appreciated. Thanks in advance

채택된 답변

Raunak Gupta
Raunak Gupta 2020년 3월 16일
Hi,
You can use textscan while reading specific line from the text file and in this case it’s the 4th line. Since there is some initial whitespaces in the 4th line which will go after reading from textscan I have added a tab character which compensates for same.
The following code may help you achieved the same.
  1. Reading 4th line and creating the changed version based on userInput1 and userInput2.
  2. Writing all the lines in a new file with changed 4th line.
userInput1 = 50; % User Input 1
userInput2 = 0.5; % User Input 2
% Original File
fid=fopen('check_nf.txt','r');
linenum = 4;
C = textscan(fid,'%s',1,'delimiter','\n', 'headerlines',linenum-1);
line_4_words = strsplit(string(C{1}));
line_4_words(3) = num2str(userInput1);
line_4_words(4) = num2str(userInput2);
changedLine = sprintf('\t') + join(line_4_words) + newline;
fclose(fid);
count = 1;
fid=fopen('check_nf.txt','r');
% New File
fod=fopen('new_nf.txt','w');
while ~feof(fid)
if count == 4
fprintf(fod,'%s',changedLine);
fgets(fid);
else
fprintf(fod,'%s',fgets(fid));
end
count = count + 1;
end
fclose(fod);
fclose(fid);
  댓글 수: 2
RAKESH KUMAR TOTA
RAKESH KUMAR TOTA 2020년 3월 16일
Thanks a lot Raunak Gupta.. It really saved lot of time.
What if i dont know which line is that to enter input file ? Here i know i have to edit in 4th line. how to generalize it. Next to write in the same input file what is the command.
RAKESH KUMAR TOTA
RAKESH KUMAR TOTA 2020년 3월 16일
How to trigger system command by writing code in matlab by not giving every time y to the file when we execute. The following message appears in command prompt
Are filenames correct?( y or n; r = redefine all, s = stop) : (user have to enter here y to run the system command)
How matlab run by itself automatically system command without user input y or n instead of that matlab should run the system command.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by