This should do the trick:
mean(mean(Z(Z(:,1)==1,2:3)))
Question
For a given matrix Z
and assuming the first column refers to index values, is it possible to find the mean of Z(:,2:3)
based on the index values in the first column Z(:,1)
.
Z = [1 3 4
2 7 8
1 3 9
3 4 4
1 5 7]
So how can I loop over Z
to find the mean of corresponding rows with index value 1 (in the first column) i.e finding the mean of Z1
Z1 = 3 4
3 9
5 7
Please can anyone help by explaining how to do this?
Solution
This should do the trick:
mean(mean(Z(Z(:,1)==1,2:3)))
OTHER TIPS
How about:
mean([accumarray(Z(:,1), Z(:,2),[],@mean), accumarray(Z(:,1), Z(:,3),[],@mean)]')'
It gives you the mean corresponding to each number. i.e. row one of the result is the mean for rows corresponding to 1
, row two is for 2
etc
Bsxfun
appproach -
Zc = [Z(:,1) mean(Z(:,[2 3]),2)]
ind1 = bsxfun(@eq,Zc(:,1),min(Zc(:,1)):max(Zc(:,1)))
mean_values = sum(bsxfun(@times,ind1,Zc(:,2)))./sum(ind1,1)
Output -
mean_values =
5.1667 7.5000 4.0000
To do that for every index in column 1, all at once:
>> accumarray(repmat(Z(:,1),size(Z,2)-1,1), reshape(Z(:,2:3),[],1), [], @mean)
ans =
5.1667
7.5000
4.0000