# 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)
Nieves Lopez on 29 Nov 2018
Commented: Nieves Lopez on 30 Nov 2018
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?

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
Nieves Lopez on 30 Nov 2018
Thank you very much!

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 CommentsShowHide 1 older comment
Bruno Luong on 29 Nov 2018