find the location of the max of a matrix when another matrix equals 0 in matlab

main.m
% Matrices
A = [1 3 2; 5 4 8; 0 2 6]; % matrix where max value will be found
B = [1 0 1; 0 0 0; 1 0 0]; % matrix to find locations where B is 0

% Finding max value and location
max_val = -Inf; % initialize max value to negative infinity
max_loc = [0 0]; % initialize max location to [0 0]
for i = 1:size(A,1)
    for j = 1:size(A,2)
        if B(i,j) == 0 && A(i,j) > max_val
            max_val = A(i,j); % update max value
            max_loc = [i j]; % update max location
        end
    end
end

% Displaying results
disp(['Max value: ' num2str(max_val) ' at location: ' num2str(max_loc)])
596 chars
19 lines

Explanation:

  • We have two matrices A and B. We want to find the location of the maximum value in A where the corresponding value in B equals 0.
  • We initialize max_val to negative infinity and max_loc to [0 0].
  • We loop through each element of A and B. If the element in B equals 0 and the element in A is greater than max_val, we update max_val and max_loc.
  • We display the maximum value and its location.

Note: If there are multiple locations where the value is the maximum, this code will only return one of those locations.

gistlibby LogSnag