Tak
Tak

Reputation: 3616

Get the average value in multiple text files Matlab

I have 10 .txt files. Each one has 100 lines, where each line has 4 values separated by commas as shown below are the first 4 lines in one of the file, but all are of the same structure:

792.98,419.48,333.35,245.63
787.13,408.59,345.05,251.48
798.3,414.17,333.36,245.63
803.61,414.43,333.35,239.78

I want get the average of each value in the 10 files For example I'll read the first line in the 10 files, and as explained before the line will have 4 values separated by ,, so I want to take the first value in the parsed line and get the average of this value in the 10 files, then save it in a result file, then move to the second value in the line and get the average then save it after the last result, and so on. So the result file will have the same structure as the 10 files (100 row, each row has 4 values separated with ,)but will hold the average of each value on the 10 files.

So if anyone could please advise.

Upvotes: 0

Views: 630

Answers (1)

Marcin
Marcin

Reputation: 238159

You can read all the files and make 3D matrix, and use mean to calculate the mean along the third dimension. For example,

% your input files. In your case you would have 10 file names here.
files = {'file_01.txt', 'file_02.txt', 'file_04.txt', 'file_04.txt'};


dataFromFiles = [];


for fi = 1:numel(files)
    dataFromFiles(:, :, fi) = dlmread(files{fi});

end


dataMean = mean(dataFromFiles, 3);

dlmwrite('mean.txt', dataMean);

Upvotes: 2

Related Questions