필터 지우기
필터 지우기

How do I continuously write to a file by using a loop?

조회 수: 13 (최근 30일)
yc j
yc j 2016년 1월 25일
댓글: Geoff Hayes 2016년 1월 26일
Hello, I have a question about continuously writing to a file, not over writing by using a loop.
For simple example, I have a code as below:
for i=1:5
a=i;
b=a*2;
AA = [a; b];
fileID = fopen('AB.txt','w');
fprintf(fileID,'a','b');
fprintf(fileID,'%12.8f %12.8f\n',AA);
fclose(fileID);
end
I want AB.txt to have all the values like a=[1 2 3 4 5] and b=[2 4 6 8 10]
However, above code will only write a=5 and b=10, and i guess this is due to overwriting.
1. How can I get the data continuously? I have to use the loop.. Above is just a very simple example.
2. If I only want the values of a to be on the text file, how should I make the code?(the examples I could find always have two sets(a & b) of data.

채택된 답변

Geoff Hayes
Geoff Hayes 2016년 1월 26일
편집: Geoff Hayes 2016년 1월 26일
Open the file and write the header outside of the for loop. Then within the loop, write the two elements to file. Then, once all iterations have completed, close the file (again outside of the for loop).
  댓글 수: 2
yc j
yc j 2016년 1월 26일
damn.... I feel like an idiot...
Thank you very much for the answer!
Geoff Hayes
Geoff Hayes 2016년 1월 26일
Glad to have been able to help!

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by