load several .mat files with n x n matrices and compute average

1 回表示 (過去 30 日間)
Michael02139
Michael02139 2016 年 10 月 13 日
コメント済み: Michael02139 2016 年 10 月 13 日
Hi there,
I'm new to working with matlab. I have experience with bash shell scripts. I have a bunch of .mat files that contain n x n matrices like this toy example:
>> load('matrix1.mat')
>> load('matrix2.mat')
>> m1
m1 =
1 2 3
2 1 5
3 6 1
>> m2
m2 =
1 3 5
2 1 5
4 9 1
I have two questions:
1. How can I automatically loop through -say- 100 of these to load them into matlab?
2. If they are loaded (in some way), how can I perform calculations on the cells in the matrices such as computing the average across them? In the example below I'm looking for
mAVG =
1 2.5 4
2 1 5
3.5 7.5 1
Thanks so much!

採用された回答

Walter Roberson
Walter Roberson 2016 年 10 月 13 日
If the variables are all the same 2D size, then the most efficient thing to do is load them one at a time and store the value into a slice of an array. Then once you have all of the data loaded, you can mean() across the third dimension.
dinfo = dir('matrix*.mat');
nfile = length(dinfo);
if nfile == 0
avg = [];
warning('There were no input files');
else
filestruct = load(dinfo(1).name);
fn = fieldnames(filestruct);
thisvar = filestruct.(fn{1});
orig_size = size(thisvar);
input_data = [thisvar(:), zeros(numel(thisvar), nfile-1, class(thisvar))];
for K = 2 : nfile
filestruct = load(dinfo(K).name);
fn = fieldnames(filestruct);
thisvar = filestruct.(fn{1});
if ~isequal(size(thisvar), orig_size)
error('file "%s" has a different size of matrix than the first file "%s"', dinfo(K).name, dinfo(1).name);
end
input_data(:,K) = thisvar(:);
end
input_data = reshape(input_data, [orig_size, nfile]);
avg = mean(input_data, ndim(input_data));
end
(with data of an unknown number of dimensions, it turned out to be easiest to store the data as columns and reshape afterwards.)
  4 件のコメント
Walter Roberson
Walter Roberson 2016 年 10 月 13 日
Yes, sorry, MATLAB is inconsistent between nelem (no 's') and 'ndims' (with 's'), and I keep getting them wrong because of that.
Michael02139
Michael02139 2016 年 10 月 13 日
Perfect!! Thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by