Find first k largest elements?

조회 수: 12 (최근 30일)
Rubel Ahmed
Rubel Ahmed 2021년 8월 13일
댓글: Matt J 2021년 8월 13일
Hi all
I have an array say A = [1 5 7 4 8 10 14]. I want to find most largest, second most largest and 3rd most largest elements from A.
I have figured out that it can be done using maxk function which is abailable for update version of Matlab but I am using R2017a where maxk function is not availablle.
Anyway, I want to see the output like Ans = [14 10 8]. Please help.Thanks in advance.

채택된 답변

Matt J
Matt J 2021년 8월 13일
편집: Matt J 2021년 8월 13일
The efficient way would probably be to use a File Exchange MEX alternative to maxk() like this,
but you could also do,
A = [1 5 7 4 8 10 14];
B=sort(A,'descend');
B=B(1:3)
B = 1×3
14 10 8
  댓글 수: 2
Rubel Ahmed
Rubel Ahmed 2021년 8월 13일
@Matt J thanks but I have figured out this is also useful
[~, idx] = sort(A);
ans = A(sort(idx(end-2:end)));
Matt J
Matt J 2021년 8월 13일
I wouldn't recommend that.
A=rand(3e7,1);
tic;
B=maxk(A,3);
toc
Elapsed time is 0.039257 seconds.
tic;
B=sort(A,'descend');
B=B(1:3);
toc;
Elapsed time is 1.968519 seconds.
tic;
[~,idx]=sort(A);
B=A(idx(end:end-2));
toc
Elapsed time is 2.338227 seconds.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

태그

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by