Reputation: 441
I'm optimizing my codes. Now I have an MxN matrix, and I want to generate a mean MxN matrix which is the mean of other rows
for example: if i have matrix A:
1 2 3
3 4 5
2 3 2
In the new matrix B, I want each one is the mean of other rows.
mean(row2,row3)
mean(row1,row3)
mean(row1,row2)
I've think of many ways, but can't avoid a loop
for row=1:3
temp = A;
temp(row,:) = [];
B(row,:) = mean(temp);
end
any thoughts?
Upvotes: 1
Views: 75
Reputation: 221534
Simple with bsxfun
-
B = (bsxfun(@minus,sum(A,1),A))./(size(A,1)-1)
The trick is to subtract the current row from the sum all rows with bsxfun
in a vectorized manner, thus giving us the sum of all rows except the current one. Finally, get the average values by dividing them by the number of rows minus 1
.
Upvotes: 2