Write to file inside a loop
조회 수: 7 (최근 30일)
이전 댓글 표시
I have this program where I open a file and write data points in it but the problem is I have to do that inside a loop. it goes:
file1=importdata('myfile.txt','%s')
for k=1:1:128
fid=fopen('myfile2.txt','w+') % I write input to that file and pass it to my
exe file
fprintf(fid,'input1')
fprintf(fid,'input2')
fprintf(fid,'input3')
the 4th input (input4) is being taken from a diff file.txt
input4=sscanf(file1{k},'%s')
Val=str2double(input4)
fprintf(fid,'%.3f',Val)
fclose(fid)
[status,result]=system('command<myfile2.txt')
M= sscanf(result,'%s')
more_result=[ Val M]
Fid2=fopen(myfile3.txt,'w+')
frpintf(Fid2,'%s', more_result)
end
Then I sscanf the results to get the a specific value (M) that I want. and I want to write Val and Z in another file but I only get the last value of each in the file. because fopen(fid,'w+') keep updating inside the loop. using a+ plus doesn't help and it keeps appending and never updates after the program is done running. RIght now I am using a+ then I manually delete the content of that file after i'm done running..writing outside the loop gives me error. is there a way I can clear the file after each run? Thanks
댓글 수: 0
답변 (2개)
Walter Roberson
2013년 3월 7일
Use 'a+' to append. You can delete() the file when appropriate, and 'a+' will create it if need be.
댓글 수: 0
Mini Me
2013년 3월 7일
댓글 수: 2
Walter Roberson
2013년 3월 7일
What is the difference between "only save the last data points" and "want it only to update after everytime I run it" ?
참고 항목
카테고리
Help Center 및 File Exchange에서 Environment and Settings에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!