MATLAB: Array Indexing using logicals in higher dimensions

logical indexingMATLAB

I have a 3D array: A = 10x10x100 where the 2D data (10×10) is stacked in the 3rd dimension.
I am using a logical mask: B which is 10×10 and has 1s at the locations where I want to access the data in every 2D slice of the 3D array.
I would like to use the logical mask to access the data from each 2D slice and perform some simple operations – such as compute mean – for all slices (in the 3rd dimension). I am currently using a for loop as below.
for i = 1:size(A,3)
temp = A(:,:,i);
mean_out(i) = mean(temp(B));
end
Is it possible to achieve this without a for loop?
Thanks.

Best Answer

Try this
mean_val = squeeze(mean(A.*B, [1 2]))
Similarly
squeeze(max(A.*B, [], [1 2])) % maximum value
squeeze(min(A.*B, [], [1 2])) % minimum value