0

Suppose in MATLAB I have a real matrix A which is n x m and a binary matrix B of the same size. The latter matrix defines the optimization set (all indices for which the element of B equals one): over this set I would like to find the maximal element of A. How can I do this?

The first idea I had is that I consider C = A.*B and look for the maximal element of C. This works fine for all matrices A which have at least one positive element, however it does not work for matrices with all negative elements.

1 Answer 1

2

You can do

C = A(B==1);

to give you an array of just the values of A corresponding to a value of 1 in B. And

max( C )

will give you the maximum value of A where B is 1

With this method you don't run into a problem when all values of A are negative as the zeros don't appear in C.

Obviously you can condense this to

desiredValue = max(A(B(:)==1));

I am using the colon operator to make sure that the result of A(B(:)==1) is a column vector - if B is all ones I am not sure if Matlab would return a vector or a nxm matrix (and I can't confirm right now).

update to get the index of the value, you can do:

f = find(B==1);
[m mi] = max(A(f));
maxIndex = f(mi);

And to get that back to the 2D elements:

[i j] = ind2sub(size(A), maxIndex);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but I am interested in the element, not in the value per se. Would it be possible to update your solution to that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.