0

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]
Eitan T
  • 32,660
  • 14
  • 72
  • 109
  • @Shai Not exactly a duplicate. The idea is similar, but here the two largest elements can have the same value... – Eitan T Mar 08 '13 at 08:20

2 Answers2

2

Your line of action should be:

  1. Sort the matrix in descending order and obtain the order of the indices of the sorted elements.
  2. 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
Eitan T
  • 32,660
  • 14
  • 72
  • 109
1
>> 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
Sam Roberts
  • 23,951
  • 1
  • 40
  • 64