Home > Blockchain >  Average array of double across separate mat files
Average array of double across separate mat files

Time:06-02

I have 10 different datasets and under each dataset there is a .mat file saved which opens a structure with several fields. Following several fields in the structure there is cell of a 15x15 double, named outcome.series.average{1,1}. How can I compute the average of this double across all datasets?

An example array would be:

x = randi(1000, 15, 15);

So I have such a double 10 times under different datasets, and the double is named in the same way for all datasets. The code needs to loop through the datasets and keep in memory the array and then compute a new double array of their average and save it as a mat file but I have been unable to do so.

Below is a draft idea of the code:

outputdir = ['D:\Jake\Discounting\Analysis365\Datasets\'];
sets = [1:10];

for set = sets
    dataset =[ 'Set', num2str(set)];
    
    dir = [outputdir dataset '\'];
    
    filename = 'results.mat';
    results = load([dir filename]);
    
    % results is now a structure in which
    % results.outcome.series.average{1,1} is a 15x15 double 
    
    % Final outcome (the finalDouble) will be a mat file of a 15x15 double which is the
    % average of all the doubles from all datasets
    
    FinalDouble = save([outputdir finalmatfile]);

end

CodePudding user response:

outputdir = 'D:\Jake\Discounting\Analysis365\Datasets\'; % ' % No need for square brackets
sets = (1:10);  % No need for square brackets

combined_sets = zeros(15,15, numel(sets)); % Initialise collection


for set = sets
    dataset =[ 'Set', num2str(set)];
    % dir() is a built-in, don't shadow it
    my_dir = [outputdir dataset '\']; % ' % Just to fix highlighting on SO
    
    filename = 'results.mat';
    results = load([my_dir filename]);
    
    % results is now a structure in which
    % results.outcome.series.average{1,1} is a 15x15 double 
    combined_sets(:,:, set) = results.outcome.series.average{1,1};
end

average_set = mean(combined_sets,3);

First, set up a collection matrix of size 15,15,numel(sets) to concatenate all sets. Then, use the third input argument of mean(A, dim), i.e. the dimension to operate over, to average over the concatenated sets to return your average 15-by-15 matrix.

I've also made some small changes and have commented them on coding style.

  • Related