How to store some values ​​in a txt file from a loop?

1 view (last 30 days)
file = dir ('*.dat')
for i = 1: lenght(file);
data = fopen(file(i).name);
soil = fread(data,[1000 1000], 'float32');
teste = find(soil<0);
soil(teste) = NaN;
soil_end = soil/6;
save (soil_end)
end
I have an .m file that opens binary data and extracts soil information from it and divides the values ​​found by 6. I would like to store the value of each loop interaction. However, after each loop, the previous value is overwritten, is there a way I can save them all in a .txt file?
Many thanks in advance for your help!
  4 Comments
matquest
matquest on 31 Mar 2020
You can add a couple of lines to your code to save the values:
fid = fopen('saved_data.txt', 'w'); % open the output .txt file for writing
file = dir('*.dat');
for ii = 1:length(file)
data = fopen(file(ii).name);
soil = fread(data, [1000 1000], 'float32');
fprintf(fid, '%f\n', soil); % this will save the value in the soil variable to the .txt file
...
end
fclose(fid) % close the output .txt file
Also note that matlab uses the values i and j as imaginary numbers, so they recommend that you use something else for your index (you'll often see ii or idx used instead).

Sign in to comment.

Answers (0)

Categories

Find more on Agriculture 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!