Another way is to ignore indexes from max :
indices2 = M1 == repmat(M1max,[1,1,size(M1,3)]); result = reshape(M2(indices2),size(M1max));
Compared to doubling, there may be a problem with accuracy. In this case, you can do
indices2 = repmat(M1max,[1,1,size(M1,3)]) - M1 < eps;
In addition, there will be a problem with this code if in M1 in the 3rd dimension there are several identical maximum values. We can catch this case with
assert(sum(indices2(:))==numel(M1max),'Multiple maximum values found')
source share