find the max of a matrix when another matrix equals 1 in matlab

To find the max of a matrix when another matrix equals 1 in Matlab, we can use the element-wise multiplication of the two matrices and then find the max value in the resulting matrix using the max() function. Here's an example code:

main.m
% sample input matrices
A = [4 5 6; 1 2 3; 9 8 7];
B = [0 0 1; 1 0 0; 0 1 0];

% find the max of A where B equals 1
C = A .* B; % element-wise multiplication
max_val = max(C(:)); % flatten the matrix and find the max value

% display the result
disp(['The max value of A where B equals 1 is: ' num2str(max_val)]);
314 chars
11 lines

In this example, we have two matrices A and B where we want to find the max value in A where B equals 1. We use the element-wise multiplication (.* operator) to create a matrix C that is the same size as A and B, such that C(i,j) = A(i,j) * B(i,j) for all i and j. This matrix C will have zeros wherever B is zero, and the corresponding elements of A will not contribute to the max value calculation.

We then use the max() function on the flattened matrix C to find the maximum value. The result is displayed using the disp() function.

Note that this method assumes that there is at least one element in A where the corresponding element in B equals 1. If not, the result will be zero.

gistlibby LogSnag