fprintf inside loops: How to write to text file or Excel?
7 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
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 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
0 Comments
More Answers (1)
See Also
Categories
Find more on Environment and Settings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!