Process file sets and store output in table rows

I have a total of 100 files. I need to calculate the mean of each column in every set of 5 files (1-5, 6-10, etc.) and store those values in arrays to display in a table. Currently, the code below calculates the mean of each column in the first 5 files, stores those values as an array, and displays them in one row of a table. However, I need help adding the arrays from files 6-10 etc. to the 2nd row etc. of the table. Any suggestions?
directory='/directory/files/';
files=dir([directory,'*.csv']);
means = [];
for i=1:5;
data=csvread([directory,files(i).name],1,0);
means=[means mean(data)]
end
array2table(means)

Answers (1)

Jan
Jan on 12 Feb 2017
Edited: Jan on 12 Feb 2017
You can try something like this, which uses two counters to collect the data of 5 files and store them in a cell:
MeanC = cell(1, numel(files) / 5);
iMeanC = 0;
aMean = zeros(1, 5);
iMean = 0;
for iFile = 1:numel(files)
% [EDITED, Typo: i -> iFile]
data = csvread(fullfile(directory, files(iFile).name), 1, 0);
iMean = iMean + 1;
aMean(iMean) = mean(data, 1); % Along 1st dimension
if iMean == 5
iMeanC = iMeanC + 1;
meanC{iMeanC} = aMean;
iMean = 0;
end
end
% Care for last chunk if number of files is not a multiple of 5:
if iMean ~= 0
iMeanC = iMeanC + 1;
meanC{iMeanC} = aMean;
end

3 Comments

When I run the code provided in the answer, I get the following error:
Subscript indices must either be real positive integers or logicals.
data = csvread(fullfile(directory, files(i).name), 1, 0);
Any ideas how to correct this?
@AG: Thanks for finding this typo: i -> iFile . This is fixed now.
Now I get this error:
In an assignment A(:) = B, the number of elements in A and B must be the same.
Error in program (line 13) aMean(iMean) = mean(data, 1); % Along 1st dimension

Sign in to comment.

Categories

Asked:

AG
on 12 Feb 2017

Commented:

AG
on 12 Feb 2017

Community Treasure Hunt

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

Start Hunting!