if a matrix equals zero, find the location of the max in another matrix in matlab

Here is the code to find the location of the maximum element in a matrix "A" if another matrix "B" is zero:

main.m
B = zeros(size(A)); % create zero matrix with same size as A
max_val = max(A(:)); % find maximum value in matrix A
[row, col] = find(A == max_val & B == 0, 1, 'first'); % find row and column index where A = max_val and B = 0
225 chars
4 lines

In the above code, we create a zero matrix "B" with the same size as matrix "A". Then, we find the maximum value in matrix "A" using the max function applied to the colon operator (:) which converts matrix "A" into a column vector.

Finally, we use the find function to locate the index of the first instance where matrix "A" equals the maximum value and matrix "B" equals zero. The optional third input argument is set to 'first' to return the first index only. The find function returns the row and column indices in the row and col variables.

gistlibby LogSnag