# Picking array elements based their values (largest, second largest,...)

조회 수: 3 (최근 30일)
okoth ochola 2023년 1월 26일
답변: Arif Hoq 2023년 1월 26일
Hi community. I have the following code which I intended to use to pick numbers from a matrix from the matrix based on their value such that, I can pick the largest, second largest and so forth. My problem is this, the code seems to waork only for a matrix with unique elements. In situations where the matrix has some repeated elements, the code returns wrong results. To some extent, I know where the problem is, my code first sort the numbers and arrange them in ascending order, then it picks values based on their positions pointed by the subsequent lines after sorting but not values anymore which is undesirable for me. When the code below is executed, it picks 7, 7 and 6 instead of 7, 6, 5. How can I instruct the code to pick the values based on their values and not positions after sorting. So that if the desired value is repeated, the code only pick it once and ignores the rest. Because with a large matrix it is impossible to look and correctly define the positions of the values as have done below. Am using R2016a. Please help. Thanks in advance.
Y=[1 1 0 0 6 5 4 7 7]
[ii,ii] = sort(Y);
Largest=Y(ii([end]));
Second_largest = Y(ii([end-1]));
Third_largest=Y(ii([end-2]));
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
okoth ochola 2023년 1월 26일
thanks, it worked prfectly well

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

### 채택된 답변

Arif Hoq 2023년 1월 26일
Y=[1 1 0 0 6 5 4 7 7];
a=unique(Y);
[ii,ij] = sort(a,'descend');
Largest=ii(1)
Largest = 7
second_largest=ii(1+1)
second_largest = 6
third_largest=ii(1+2)
third_largest = 5

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

### 카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

R2016a

### Community Treasure Hunt

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

Start Hunting!

Translated by