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

7 views (last 30 days)
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.

Accepted Answer

Albert Fan
Albert Fan on 17 Jul 2018
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

More Answers (1)

Bjarte
Bjarte on 17 Jul 2018
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!

Categories

Find more on Environment and Settings in Help Center and File Exchange

Tags

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!