필터 지우기
필터 지우기

fprintf inside loops: How to write to text file or Excel?

조회 수: 16 (최근 30일)
Bjarte
Bjarte 2018년 7월 17일
편집: Bjarte 2018년 7월 17일
I am working on a research project and have developed a code that loops using different input parameters. At the end of the code I use fprintf to print the final results which looks like the image below (and continues for several hundred lines). How can I write these results to a txt or Excel file? I am using fprintf within the loops which makes it difficult.

채택된 답변

Albert Fan
Albert Fan 2018년 7월 17일
You can use fopen() to open a file and then use fprintf to write to that file.
I've created a simple example:
f = fopen('test.txt', 'w')
for i=1:10
fprintf(f, "Hello: %d\n", i);
end
fclose(f)
And it looks like:
So long as you do not call fclose(), you are able to call fprintf() anywhere with f to write whatever you want to the file you've opened.
The documentation page for fopen is here
The documentation page for fprintf is here. What I've used in my example is: fprintf(fileID,formatSpec,A1,...,An), where the fileID is what is returned by fopen()
Regarding to how to save your data to excel, you can refer to this link, or you can change your code a little bit to incorporate xlswrite(), which is a function designed to write stuff to excel. Or you can write your data in csv, open in Excel, and then save it as .xls or .xlsx file

추가 답변 (1개)

Bjarte
Bjarte 2018년 7월 17일
It worked! However, I had to replace 'w' with 'a+' in order for it to not replace existing contents in the loops. Thank you very much for your help!

카테고리

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

태그

제품


릴리스

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by