How to sort an array in descending order and you also have idea about the position to which it descend ?

조회 수: 19 (최근 30일)
I have an array of any length and I want to sort them in descending order. The position and value in that matrix refer to an ID of a node. So my question is that how I can sort this array in descending order and I should have idea of node position in array after sorting out.
Like I have a matrix A and the first value of the array is 5 but its ID is 1 and second value is 4 and its ID is 2 so after descending it goes to some new position 11 and 4 to 12 in the array. then whether i can get in a variable the position of variables after sorting out.
if true
A = [ 5 4 61 7 1 3 35 67 11 44 83 48 110 6]
B = sort (A, 'descend');
B = 110 83 67 61 48 44 35 11 7 6 5 4 3 1
ID_pos of 5 = 11 and ID_pos of 4 = 12 so how to get these index automatically.
end
Kindly guide me

채택된 답변

Star Strider
Star Strider 2016년 2월 20일
Use the ismember function:
A = [ 5 4 61 7 1 3 35 67 11 44 83 48 110 6];
B = sort (A, 'descend');
[~,Idx] = ismember([5 4], B)
Idx =
11 12
  댓글 수: 2
Arsal15
Arsal15 2016년 2월 21일
Star Strider
I am really thankful for your simple and unique solution. I need one hint in another question I posted, if you can.
Star Strider
Star Strider 2016년 2월 21일
My pleasure.
I didn’t see your other Question listed on your Profile page just now, so I’ll look for it.

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

추가 답변 (1개)

Roger Stafford
Roger Stafford 2016년 2월 21일
You can use the second argument produced by 'sort':
[B,p] = sort(A,'descend');
q = 1:length(p);
q(p) = q;
The values in 'q' will give the indices with respect to 'B' of the corresponding positions in 'A'.
  댓글 수: 2
Arsal15
Arsal15 2016년 2월 21일
But this solution makes the matlab to get crash ?
I don't know why ?
Roger Stafford
Roger Stafford 2016년 2월 21일
I don't know why either. On my computer I get the result
q =
11 12 4 9 14 13 7 3 8 6 2 5 1 10
which I believe is the solution you wished to obtain.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by