Effacer les filtres
Effacer les filtres

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

16 vues (au cours des 30 derniers jours)
Bjarte
Bjarte le 17 Juil 2018
Modifié(e) : Bjarte le 17 Juil 2018
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.

Réponse acceptée

Albert Fan
Albert Fan le 17 Juil 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

Plus de réponses (1)

Bjarte
Bjarte le 17 Juil 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!

Tags

Produits


Version

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by