Identifying and modifying the maximum in a matrix.

I have a 100 by 200 matrix of random numbers. I want to identify the max number in each row and set it to 1, while setting everything else equal to 0.
Im able to identify the max, but currently unable to set up the for loop to modify the matrix.
Is anyone able to help?

답변 (2개)

KSSV
KSSV 2018년 6월 6일
A = rand(100,200) ;
iwant = zeros(size(A)) ;
[m,n] = size(A) ;
for i = 1:m
[val,idx] = max(A(i,:)) ;
iwant(i,idx) = 1 ;
end
Stephen23
Stephen23 2018년 6월 6일
편집: Stephen23 2018년 6월 6일
This is MATLAB, so no loops are required for this task. It is easy in just one line:
>> M = randi(9,10,20) % fake data
M =
3 6 7 2 2 2 6 2 2 5 6 6 6 7 2 4 7 4 4 4
9 1 5 7 8 5 7 4 5 9 8 6 6 1 6 5 7 2 5 4
4 1 1 7 3 7 6 6 4 7 2 3 3 3 9 8 1 5 1 8
5 2 1 6 9 9 3 6 4 7 3 6 7 2 8 3 4 9 3 3
7 2 2 8 1 6 9 4 9 1 5 4 2 2 8 7 8 2 7 9
2 8 5 9 6 5 7 5 1 8 5 2 1 2 2 1 3 5 9 9
2 2 9 6 9 6 5 6 3 3 2 8 6 8 1 1 1 1 9 9
6 6 2 8 4 8 8 7 6 9 1 4 4 9 4 3 6 9 7 2
2 9 2 2 4 7 8 9 2 9 6 7 1 7 5 3 7 4 5 8
6 4 8 6 9 7 2 9 7 3 7 3 3 1 7 9 3 8 1 6
>> M(:) = bsxfun(@eq,M,max(M,[],2))
M =
0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0
1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1
0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0
0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0
This marks every instance of the maximum values in the row, If you only want to mark the first instance of the maximum value in the row, then this is also easy:
>> M(:) = M & cumsum(M,2)==1
M =
0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0

이 질문은 마감되었습니다.

태그

질문:

2018년 6월 6일

마감:

2021년 8월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by