如何在数组中找到n个最大元素并使其他元素为零? [英] How to find n largest elements in an array and make the other elements zero in matlab?
本文介绍了如何在数组中找到n个最大元素并使其他元素为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个矩阵
A=[2 3 4; 6 1 2]
我想找到2个最大的元素,并将所有其他元素设为零. 在这种情况下,A最终变为
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]
推荐答案
您的行动方针应该是:
- 以降序对矩阵进行排序,并获得已排序元素的索引的顺序.
- 舍弃前两个索引,并使用其余的索引将
A
中的相应元素清零.
- 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
.
示例
A = [2 3 4; 6 1 2];
[Y, idx] = sort(A(:), 'descend')
A(idx(3:end)) = 0
这应该导致:
A =
0 0 4
6 0 0
这篇关于如何在数组中找到n个最大元素并使其他元素为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文