MATLAB: How to populate a 3-D matrix with maximum values along the 3rd dimension of another 3-D matrix

MATLAB: How to populate a 3-D matrix with maximum values along the 3rd dimension of another 3-D matrix

indiceslinearMATLABmax

I am finding the maximum values across the 3rd dimension of a 3-D matrix. Now I would like to set all the other values — the values that are not the maximum across the 3rd dimension — of this matrix to zero. I am trying to use the second output argument of the “max” function, but I am not getting what I want. How would I go about this? My code is: 
 
% Create random 3-D matrix
A = rand(4,4,3);
% Get maximum at each (i,j)-coordinate along the 3rd dimension
[val,ind] = max(A,[],3);

Best Answer

  • The following code snippet uses a double “for” loop to iterate over the (i,j) coordinates of the “ind” matrix. A vectorized method would work unlike in the 2-D case. 
     
    % Fill only with the maximum value
    B = zeros(size(A));
    for i=1:size(A,1)
    for j=1:size(A,2)
    B(i,j,ind(i,j)) = A(i,j,ind(i,j));
    end
    end
  • Add a Comment

    Your email address will not be published. Required fields are marked *