calculate the mean of a matrix by the first column

1 回表示 (過去 30 日間)
yue li
yue li 2019 年 1 月 24 日
コメント済み: yue li 2019 年 1 月 24 日
Hello,
I just leaned MATLAB.
I want to calculate the mean of a matrix by the first column:
Input:
1 9 7 5 7
2 1 1 1 3
2 5 5 4 4
3 1 1 1 3
3 5 5 4 4
3 1 1 1 3
3 5 6 4 4
4 1 8 1 3
4 5 5 4 4
5 1 5 1 3
6 1 4 1 3
7 5 5 4 4
Output:
1 9 7 5 7
2 3 3 2.5 3.5
3 3 3.25 2.5 3.5
4 3 6.5 2.5 3.5
5 5 1 5 1
6 6 1 4 1
7 7 5 5 4
My code:
G = findgroups(M(:,1 ));
Out = [unique(M(:,1)) splitapply(@mean, M(:,2:end), G)]
Error using vertcat
Dimensions of matrices being concatenated are not consistent.
Error in splitapply>localapply (line 257)
finalOut{curVar} = vertcat(funOut{:,curVar});
Error in splitapply (line 132)
varargout = localapply(fun,splitData,gdim,nargout);
Thanks in advance for any suggestions and help!
Yue

採用された回答

Matt J
Matt J 2019 年 1 月 24 日
Out = [unique(M(:,1)) splitapply(@(z)mean(z,1), M(:,2:end), G)]
  1 件のコメント
yue li
yue li 2019 年 1 月 24 日
Hello, Matt J,
This works!
Thank you so much fro your great help!
With Best!
Yue

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

その他の回答 (1 件)

Matt J
Matt J 2019 年 1 月 24 日
編集済み: Matt J 2019 年 1 月 24 日
Or, with tables,
Out=varfun(@mean,array2table(M),'GroupingVariables','M1');
Out(:,2)=[],

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by