Maximum value of matrix

2 views (last 30 days)
mingcheng nie
mingcheng nie on 29 Oct 2022
Commented: mingcheng nie on 29 Oct 2022
Hi there,
If we have a complex matrix A, size of (N,M), is there any efficient way to keep the maximum 6 absolute values in A and set others to be zeros? like abs(A(n,m)), keep the top6 biggest one, then set rest to 0.
Really appreciate for anyone leave a comment.

Accepted Answer

Kevin Holly
Kevin Holly on 29 Oct 2022
% Generate random matrix
N = 34;
M = 23;
A = rand(N,M);
% Sort from highest to lowest
values = sort(abs(A(:)), 'descend')
values = 782×1
0.9998 0.9985 0.9980 0.9971 0.9965 0.9962 0.9950 0.9924 0.9914 0.9913
% top 6
values(1:6)
ans = 6×1
0.9998 0.9985 0.9980 0.9971 0.9965 0.9962
values(6)
ans = 0.9962
B = (A>=values(6)).*A
B = 34×23
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.9980 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.9985 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
imshow(B)
  3 Comments
Kevin Holly
Kevin Holly on 29 Oct 2022
I would appreciate it if you could accept this answer.
mingcheng nie
mingcheng nie on 29 Oct 2022
sure definitely

Sign in to comment.

More Answers (0)

Tags

Products


Release

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!