MATLAB: Find rows with maximum number and replace them with 1

MATLAB: Find rows with maximum number and replace them with 1

find rows with maximum number and replace them with 1

I have a matrix with n rows and 1 column. I would like to find row which have the maximum number. Then, replace 1 in these rows and replace 0 in other rows.
For instance: I have matrix A and I would like to produce matrix B.
A=
5
0
0
4
3
0
B=
0
1
1
0
0
1

Best Answer

  • A = [5;0;0;4;3;0];
    [cnt,idx] = histc(A,unique(A));
    [~,idz] = max(cnt);
    B = idx==idz;
    outputs this
    >> B
    B =
    0
    1
    1
    0
    0
    1
    and A = [1;1;0;4;3;1]; outputs this:
    >> B
    B =
    1
    1
    0
    0
    0
    1
  • Add a Comment

    Your email address will not be published. Required fields are marked *