フィルターのクリア

Mean of mutiple variables

1 回表示 (過去 30 日間)
ali akbar
ali akbar 2020 年 12 月 11 日
コメント済み: dpb 2020 年 12 月 11 日
I have 5 '.mat' data files where each datafile contains 1 by 19 cell (each cell size = 512 by 9). I wanted to find the mean of the 4th column of 1st cell from all 5 data files.
Here is a look at the code.
load('data1a.mat');load('data2.mat');load('data3.mat');load('data4.mat');load('data5.mat');...
% Extracting the 4th column
a=data1a{1,1}(:,4);b=data2{1,1}(:,4) and so on...
m=(a+b+c+d+e)/5
Now people in stoneage might used to do this kind of laborious exercise. I am wondering if anyone could give a one/two liner answer for finding mean which is not naive like mine.
  4 件のコメント
Stephen23
Stephen23 2020 年 12 月 11 日
Copy and pasting code like this is a sign that you are doing something wrong:
load('data1a.mat');load('data2.mat');load('data3.mat');load('data4.mat');load('data5.mat');...
Learn to use arrays and indexing! For example:
ali akbar
ali akbar 2020 年 12 月 11 日
please see attached.

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

採用された回答

dpb
dpb 2020 年 12 月 11 日
編集済み: dpb 2020 年 12 月 11 日
d=dir('data*.mat'); % or similar list. Name files so can use appropriate wildcard expression
total=0;
for i=1:numel(d)
data=load d(i).name;
total=total+structfun(@(x)sum(x{1}(:,4)),data);
end
mn=mean(total);
Above does the summation; same result if were to use mean in the anonymous function as well if same number elements in each cell array.
If the variables were named consistently would be easier to code; above handles whatever they are inside the .mat files as long as just one variable per file.
  2 件のコメント
ali akbar
ali akbar 2020 年 12 月 11 日
thank you. matlab throwing a syntax error on the second line of the 'for' loop.
dpb
dpb 2020 年 12 月 11 日
so, debug it. (Exercise for Student :) )
Accidentally wrote it as command syntax instead of function form needed.

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by