0

How do I use max function to set the value of the highest element in a vector to 1? For example, let A be a matrix of size 3 rows and 2 columns. I want to set A(:,1) = [0.9 0.03 0.01]' to B(:,1) = [1 0 0]. Repeating the same for the second column of A. So, I should get B = [1 0 0; 0 1 0]. So, I could obtain the index of the maximum element in each column. I don't know how to assign and change the value.This is what I could do. Please help.

A =

    0.9000    0.1000
    0.0300    0.5800
    0.0100    0.0020

>> [ans,ind] = max(A)

ans =

    0.9000    0.5800


ind =

     1     2
0

1 Answer 1

3

max returns the index within each column. Thus the subscripts you want to set are given by i = ind and j = 1:size(A,2), the second just indexes each column. Unfortunately, B(i,j) does not do what you want in this case, it indexes each combination of i and j.

sub2ind converts subscripts to linear indices:

lin = sub2ind(size(A), ind, 1:size(A,2))

should return the vector [1,5]. Linear indices run along columns. B(lin) does exactly what you need:

B = zeros(size(A));
B(lin) = 1;

At the expense of a bit more computation, you can simplify the above a lot. For newer versions of MATLAB, that do implicit singleton expansion, you can do:

B = A == max(A);

Here we just find, for each column, the element that matches the maximum for that column, and set it to true (which has a value of 1). If your version of MATLAB does not support implicit singleton expansion, you can use bsxfun to accomplish the same things:

B = bsxfun(@eq, A, max(A));
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. The first option works but the second option B=A==max(A) throws error which is Error using == Matrix dimensions must agree. I have MATLAB 2011Rb version. Is it something to do with this version of MATLAB that I get this error?
@SrishtiM: Yes, as I mentioned, that syntax only works for newer versions of MATLAB. In this case "newer" means from the last two or three years. Try the bsxfun option, it will work with your version of MATLAB.

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.