Reputation: 31
I am using the mean
function in MATLAB on a 4D matrix.
The matrix is a 32x2x20x7
array and I wish to find the mean of each row, of all columns and elements of 3rd dimension, for each 4th dimension.
So basically mean(data(b,:,:,c)) [pseudo-code] for each b, c
.
However, when I do this it spits me out separate means for each 3rd dimension, do you know how I can get it to give me one mean for the above equation - so it would be (32x7=)224 means.
Upvotes: 2
Views: 2761
Reputation: 30579
Note that with two calls to mean
, there will be small numerical differences in the result depending on the order of operations. As such, I suggest doing this with one call to mean
to avoid such concerns:
squeeze(mean(reshape(data,size(data,1),[],size(data,4)),2))
Or if you dislike squeeze
(some people do!):
mean(permute(reshape(data,size(data,1),[],size(data,4)),[1 3 2]),3)
Both commands use reshape
to combine the second and third dimensions of data
, so that a single call to mean
on the new larger second dimension will perform all of the required computations.
Upvotes: 1
Reputation: 112659
You could do it without loops:
data = rand(32,2,20,7); %// example data
squeeze(mean(mean(data,3),2))
The key is to use a second argument to mean
, which specifies across which dimension the mean is taken (in your case: dimensions 2 and 3). squeeze
just removes singleton dimensions.
Upvotes: 3
Reputation: 2437
this should work
a=rand(32,2,20,7);
for i=1:32
for j=1:7
c=a(i,:,:,j);
mean(c(:))
end
end
Upvotes: 2