fprintf inside loops: How to write to text file or Excel?
7 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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 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 个评论
更多回答(1 个)
另请参阅
类别
在 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!