How do I open the txt files of a directory and then average the values found accross all txt files?
3 views (last 30 days)
Show older comments
In a folder are located many txt files containing 2 columns of numbers. I would like to average the numbers in the columns of each txt file. By that I mean that for instance, we take the 1s number of the 2nd column of all txt files and average that, then 2nd number, so on and so forth for all the numbers of both columns. At the end I would like to have a 2 column matrix containing all those averages.
Does anyone have an idea how to do that?
In past I've used textread and textscan to treat those 2 column txts one file at a time. So I used to do [A,B]=textread('filename.txt','%f %f'); which would store the columns in A and B for me.
I've thought about doing textread/scan with a for loop to store all the matrices and then just do another loop to average each element, but i'm not sure how to do that, or if it's efficient ...
2 Comments
Temu Gautama
on 13 Feb 2020
Hi,
Something like this should work, assuming they are all the same size: loop over files, sum, then divide
d1 = dir( '*.txt' );
xSum = 0;
for c1 = ( 1 : length( d1 ))
fid = fopen( d1(c1).name, 'r' );
x1 = fscanf( fid, '%f', [2 Inf] )';
xSum = xSum + x1;
end
xAv = xSum ./ ( length( d1 ) + eps );
Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!