find the multiple max values
45 次查看(过去 30 天)
显示 更早的评论
I have a matrix
8 23 44 19
44 5 62 1
7 6 12 33
6 55 24 8
and I want to find 3 largest values(reserve duplicate matches),and then make the other be 0
just like
0 0 44 0
44 0 62 0
0 0 0 0
0 55 0 0
I have read some book ,but I still have no idea
help me plz
采纳的回答
madhan ravi
2020-6-16
编辑:madhan ravi
2020-6-16
MaX = maxk(matrix(:), 3);
Wanted = ismember(matrix, MaX) .* matrix
% for older versions
m = sort(matrix(:),'descend');
Wanted = ismember(matrix, m(1:3)) .* matrix
11 个评论
madhan ravi
2020-6-18
In the command window just call the function
Matrix = randi(10,4); % an example
Wanted = Mx(Matrix)
% function definition
function Wanted = Mx(matrix) % save it as a separate file called Mx.m
... the Code
end
Stephen23
2020-6-18
Note that this answer does not "find 3 largest values" as the question requested:
>> matrix = [4,4,4;4,4,4;3,2,1]
matrix =
4 4 4
4 4 4
3 2 1
>> m = sort(matrix(:),'descend');
>> Wanted = ismember(matrix, m(1:3)) .* matrix
Wanted =
4 4 4
4 4 4
0 0 0
The problem is caused by the use of sort. See my answer for the correct solution.
更多回答(1 个)
Stephen23
2020-6-16
Where M is your matrix:
>> U = unique(M(:));
>> X = ismember(M,U(end-2:end));
>> M(~X) = 0
M =
0 0 44 0
44 0 62 0
0 0 0 0
0 55 0 0
3 个评论
Stephen23
2020-6-18
编辑:Stephen23
2020-6-18
"Thanks, bro this answer can work very well"
Note my answer actually gives the output that you asked for (unlike the answer that you accepted):
>> M = [4,4,4;4,4,4;3,2,1]
M =
4 4 4
4 4 4
3 2 1
>> U = unique(M(:));
>> X = ismember(M,U(end-2:end));
>> M(~X) = 0
M =
4 4 4
4 4 4
3 2 0
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!