How can I efficiently (with no loops) compute the mean of each column in a matrix, taking different elements from each column?

1 view (last 30 days)
I need to compute something similar to this:
M = [ 1 2 3 4 5; ...
6 7 8 9 10; ...
11 12 13 14 15];
idx = [ 1 2 3 2 1; ...
2 3 3 3 3];
for col=1:size(M,2),
v(1,col) = mean(M(idx(1,col):idx(2,col),col));
end;
How can I do this without the loop?

Accepted Answer

Bruno Luong
Bruno Luong on 29 Nov 2018
Edited: Bruno Luong on 29 Nov 2018
M = [ 1 2 3 4 5; ...
6 7 8 9 10; ...
11 12 13 14 15];
idx = [ 1 2 3 2 1; ...
2 3 3 3 3];
m = size(M,1);
r = (1:size(M,1)).';
sum(M.*(r >= idx(1,:) & r <= idx(2,:)),1)./(diff(idx)+1)
Result
ans =
3.5000 9.5000 13.0000 11.5000 10.0000

More Answers (1)

Bruno Luong
Bruno Luong on 29 Nov 2018
M = [ 1 2 3 4 5; ...
6 7 8 9 10; ...
11 12 13 14 15];
idx = [ 1 2 3 2 1; ...
2 3 3 3 3];
[m,n] = size(M);
mean(M(idx+(0:n-1)*m),1) % use "mean(M(bsxfun(@plus,idx,(0:n-1)*m)),1)" for R2016a or prior
Result
ans =
3.5000 9.5000 13.0000 11.5000 10.0000
  2 Comments

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!