MATLAB Answers

find the multiple max values

3 views (last 30 days)
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

  3 Comments

Aditya Verma
Aditya Verma on 16 Jun 2020
Hello, could you please specify what you have tried until now, and in which part you are facing problem.
chung yen chang
chung yen chang on 18 Jun 2020
q=[6 7 3 2
5 3 6 4
7 7 5 3
7 9 10 5]
[x,y]=sort(q(:))
q(y(1:end-3))=0
in this case matrix can't preserve max three values
chung yen chang
chung yen chang on 18 Jun 2020
the answer would be
q =
0 0 0 0
0 0 0 0
0 7 0 0
0 9 10 0

Sign in to comment.

Accepted Answer

madhan ravi
madhan ravi on 16 Jun 2020
Edited: madhan ravi on 16 Jun 2020
MaX = maxk(matrix(:), 3);
Wanted = ismember(matrix, MaX) .* matrix
% for older versions
m = sort(matrix(:),'descend');
Wanted = ismember(matrix, m(1:3)) .* matrix

  11 Comments

Show 8 older comments
chung yen chang
chung yen chang on 18 Jun 2020
Madhan I apologize for that ,I misread .Actually this a great method
madhan ravi
madhan ravi on 18 Jun 2020
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
Stephen Cobeldick
Stephen Cobeldick on 18 Jun 2020
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.

Sign in to comment.

More Answers (1)

Stephen Cobeldick
Stephen Cobeldick on 16 Jun 2020
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 Comments

chung yen chang
chung yen chang on 18 Jun 2020
Thanks, bro this answer can work very well
Stephen Cobeldick
Stephen Cobeldick on 18 Jun 2020
"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
madhan ravi
madhan ravi on 18 Jun 2020
However maxk(...) gives the right answer xD, but i do agree the loophole.

Sign in to comment.


Translated by