问题
Suppose I have a matrix
A=[2 3 4; 6 1 2]
I want to find 2 largest elements and make all the other elements zero. In this case A finally becomes
A=[0 0 4; 6 0 0]
回答1:
Your line of action should be:
- Sort the matrix in descending order and obtain the order of the indices of the sorted elements.
- Discard the first two indices and use the rest to zero out the corresponding elements in
A
.
Example
A = [2 3 4; 6 1 2];
[Y, idx] = sort(A(:), 'descend')
A(idx(3:end)) = 0
This should result in:
A =
0 0 4
6 0 0
回答2:
>> A=[2 3 4; 6 1 2]
A =
2 3 4
6 1 2
>> [~,idx] = sort(A(:), 'descend');
>> A(idx(3:end))=0
A =
0 0 4
6 0 0
来源:https://stackoverflow.com/questions/15277468/how-to-find-n-largest-elements-in-an-array-and-make-the-other-elements-zero-in-m