How to find n largest elements in an array and make the other elements zero in matlab? [duplicate]

强颜欢笑 提交于 2020-01-25 09:30:08

问题


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:

  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



回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!