Hi, I have a 5 x 5 matrix, A.
How can I create a matrix that has 1's for the largest two values in each row, and all remaining elements are zero? (I created a sort index by sort(A,2,'descend)...but am lost...).
The output matrix is a 5 x 5 matrix with 1's for the largest two values in each row.
Any help would be appreciated. Thanks!
Dan

 채택된 답변

Jan
Jan 2017년 10월 17일

2 개 추천

x = randi([0,20], 5, 5);
[~, index] = sort(x, 2, 'descend'); % Sorting index
result = zeros(size(x)); % Create output
result(sub2ind(size(x), 1:5, index(:, 1).')) = 1; % Mark largest
result(sub2ind(size(x), 1:5, index(:, 2).')) = 1; % Mark 2nd largest

댓글 수: 1

dan berkowitz
dan berkowitz 2017년 10월 17일
thank you, jan! where would humanity be without you?

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Cedric
Cedric 2017년 10월 17일
편집: Cedric 2017년 10월 17일

1 개 추천

Here is another way:
>> A = rand(5, 5)
A =
0.9337 0.1518 0.6164 0.3074 0.4584
0.9017 0.1290 0.8862 0.4706 0.3778
0.6309 0.8430 0.3314 0.1133 0.3268
0.8527 0.1393 0.8076 0.4477 0.7315
0.4614 0.8630 0.6206 0.1753 0.5531
>> idm = A == max(A, [], 2) ;
A(idm) = NaN ;
B = double( A == max(A, [], 2) | idm )
B =
1 0 1 0 0
1 0 1 0 0
1 1 0 0 0
1 0 1 0 0
0 1 1 0 0
If you have more than one max or more than one second max, you will get more than two 1 per row though. If you need to make a choice (e.g. pick the left-most occurrences), you will need to implement more logic/sorting. See below what I mean:
>> A = randi(10, 5, 5)
A =
9 3 6 5 10
9 8 9 1 10
4 5 8 2 7
1 9 9 10 9
6 7 5 4 4
>> idm = A == max(A, [], 2) ;
A(idm) = NaN ;
B = double( A == max(A, [], 2) | idm )
B =
1 0 0 0 1
1 0 1 0 1
0 0 1 0 1
0 1 1 1 1
1 1 0 0 0
Ahmed raafat
Ahmed raafat 2017년 10월 17일

0 개 추천

you mean you want only first high values in each row right??
y=zeros(size(A,1),size(A,2));
for i=1:size(A,1)
x=sort(A(i,:),descend');
y(i,1:2)=x(1:2);
end

댓글 수: 1

dan berkowitz
dan berkowitz 2017년 10월 17일
No. I want the output to be a 5x5 matrix. And there should be '1' in each row where the largest two values are. All other entries in the matrix should be '0'.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

질문:

2017년 10월 16일

댓글:

2017년 10월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by