Azzera filtri
Azzera filtri

Write to file inside a loop

24 visualizzazioni (ultimi 30 giorni)
Ali Rafiei
Ali Rafiei il 2 Lug 2019
Commentato: Rik il 4 Lug 2019
I have a loop that each time generates a value 'b1'. I want to create a matrix of all the b1 values to make a histogram at the end. The code that I found is:
q = b1;
save('pqfile.txt','q','-ascii');
this code overwrites and only the last b1 is saved on pqfile. wondering if anyone can help me not overwrite
Thanks
  1 Commento
Rik
Rik il 4 Lug 2019
@Ali, did either answer solve your issue? If so, please consider accepting the answer that works best for you, or comment with your remaining questions.

Accedi per commentare.

Risposte (2)

infinity
infinity il 2 Lug 2019
Modificato: Rik il 2 Lug 2019
Hello,
You can refer a simple solution as follows
saveb1 = [];
for (your loop)
your code to compute b1;
saveb1 = [saveb1; b1];
end
save('pqfile.txt','saveb1','-ascii');
In this method, you will save b1 of each loop to a varible saveb1. After the loop, you can save "saveb1" to the text file.

Rik
Rik il 2 Lug 2019
Or a much better practice: if you know the number of iterations you should pre-allocate your output array.
saveb1 = zeros(1,k);
for n=1:k
%your code to compute b1 goes here
saveb1(k)=b1;
end
Alternatively, if you insist of using a file write:
%prepare an empty file
fid=fopen('saveb1.txt','w');
if fid==-1
error('file could not be opened')
end
for n=1:k
%your code to compute b1 goes here
fprintf(fid,'%.1f\n',b1);
end
fclose(fid);
And now you can read the file with all the b1 values.
  2 Commenti
Ali Rafiei
Ali Rafiei il 2 Lug 2019
Thank you for your quick answer. The functon that generates b1 already has multiple loops. I was wondering if all of the loops should go into the loop you suggested above?
Rik
Rik il 2 Lug 2019
Yes it would. There might be more efficient options, but simply pasting the code that generates a value for b1 for a given value of n into that loop should do the trick. If it is a slow process you could use the file write (or a normal save/load) to check which values have already been calculated and fill those empty slots.

Accedi per commentare.

Categorie

Scopri di più su Performance and Memory in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by