replace maximum values of each row of a matrix

9 views (last 30 days)
I have a huge matrix with i rows and j columns. I would like to find the max number for each row and, then, replace 1 in these positions and 0 in the other ones. For instance, I have matrix A
A = [1 4 3 0 ;6 0 5 9; 0 1 7 1 ; 1 5 3 1]
and I would like to produce matrix B.
B = [0 1 0 0 ;0 0 0 1; 0 0 1 0; 0 1 0 0]
I would like to have a code without using loops, as I am able to do it but the procedure time ts too long

Accepted Answer

David Hill
David Hill on 17 Mar 2021
B=A==max(A,[],2);
  2 Comments
Micangi
Micangi on 22 Mar 2021
It works perfectly. However, I have an issue because there are some null rows in the "A" matrix, for instance:
A = [1 4 3 0 ;6 0 5 9; 0 1 7 1 ; 1 5 3 1; 0 0 0 0]
Hence, when I am using B=A==max(A,[],2), i get:
B= [0 1 0 0 ;0 0 0 1; 0 0 1 0; 0 1 0 0; 1 1 1 1]
How can I assign null rows in the B matrix when each row element is equal to 1? In other worlds, I would like to obtain at the end:
B=[0 1 0 0 ;0 0 0 1; 0 0 1 0; 0 1 0 0; 0 0 0 0]

Sign in to comment.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!