How to creat row mean for every three columns of a matrix?

1 view (last 30 days)
Hey there, I hope someone can help me. I want to create a matrix of the row means for every three columns of a matrix. Something like that:
A=[1 2 3 4 5 6; 1 2 3 4 5 6; 3 4 5 6 7 8; 9 10 11 12 13 14]
mean_x1= mean(A{:,[1:3]},2);
mean_x2= mean(A{:,[4:6]},2);
But I want the means to be in one matrix:
mean=[2 5; 2 5;4 7; 6.67 13]
and I have a much lager matrix with 173 columns, so I think maybe a loop would be the right thing. I just don't know how to do it at all. I hope someone understands what I am looking for.
Thanks!

Answers (1)

Guillaume
Guillaume on 8 May 2018
Don't know where that 6.67 comes from. I assume it should be 10:
mean(permute(reshape(A, size(A, 1), 3, []), [1 3 2]), 3)
Note that if you have a variable called mean then a) don't do that and b) clear it before running the above.
What the above does: reshape the variable into a 3D matrix with 3 columns, each group of 3 column now becomes a page. Permute column and pages, then calculate the mean across the pages.
  1 Comment
Anja Lauer
Anja Lauer on 9 May 2018
Yes, you are right it's supposed to be 10! And what you requested worked perfectly. Thanks a lot! (I don't call my variable mean, it was just for demonstration ;))

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!