Sorting from the maximum value to minimum value in a vector

조회 수: 77 (최근 30일)
mr mo
mr mo 2017년 11월 29일
답변: Image Analyst 2017년 11월 30일
Hi. I have a vector named A, e.g.
A=[2 5 8 7 8 9 3 7 6 5 4 1]
I want to sort the members of vector A from maximum to minimum values.
Also I want to find the indices of equal members in the sorted version of vector A.
How can I do that?
Thanks for your help.

채택된 답변

Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan 2017년 11월 29일
A=[2 5 8 7 8 9 3 7 6 5 4 1];
Asorted = sort(A,'descend'); % sorted from max to min
[~,indx] = unique(Asorted);
equalpairs = [(setdiff(1:length(Asorted),indx)-1)' setdiff(1:length(Asorted),indx)']; % each row contains pair of indices with equal values

추가 답변 (2개)

Matt J
Matt J 2017년 11월 29일
Using the UNIQUE command.
  댓글 수: 3
mr mo
mr mo 2017년 11월 29일
In the unique command I lost some of the members and I don't want that.
mr mo
mr mo 2017년 11월 29일
I want to reach this:
sortedA = [9 8 8 7 7 6 5 5 4 3 2 1]
and I want the indices of equal members in the sorted version of A, e.g.
sortedA(2)=sortedA(3)
sortedA(4)=sortedA(5)
sortedA(7)=sortedA(8)

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


Image Analyst
Image Analyst 2017년 11월 30일
With the accepted solution, if A is
A =[22 25 28 27 28 29 23 27 26 25 22 22 24 21 22]
The accepted solution gives
equalpairs =
2 3
4 5
7 8
11 12
12 13
13 14
However if you use my solution:
A = [2 5 8 7 8 9 3 7 6 5 2 2 4 1 2] + 20
sortedA = sort(A, 'descend')
props = regionprops(sortedA, sortedA, 'MeanIntensity', 'PixelIdxList');
missingNumbers = isnan([props.MeanIntensity]);
props = props(~missingNumbers); % Get rid of nans that occur when there is a missing number.
% Done! Now print them out so we can see:
for k = 1 : length(props)
fprintf('The indexes for %d are ', props(k).MeanIntensity);
fprintf('%d, ', props(k).PixelIdxList);
fprintf('\n');
equalIndexes{k} = [props(k).PixelIdxList];
end
celldisp(equalIndexes)
You will get a cell array where each cell has the indexes for a certain number:
A =
22 25 28 27 28 29 23 27 26 25 22 22 24 21 22
sortedA =
29 28 28 27 27 26 25 25 24 23 22 22 22 22 21
The indexes for 21 are 15,
The indexes for 22 are 11, 12, 13, 14,
The indexes for 23 are 10,
The indexes for 24 are 9,
The indexes for 25 are 7, 8,
The indexes for 26 are 6,
The indexes for 27 are 4, 5,
The indexes for 28 are 2, 3,
The indexes for 29 are 1,
equalIndexes{1} =
15
equalIndexes{2} =
11
12
13
14
equalIndexes{3} =
10
equalIndexes{4} =
9
equalIndexes{5} =
7
8
equalIndexes{6} =
6
equalIndexes{7} =
4
5
equalIndexes{8} =
2
3
equalIndexes{9} =
1
I think having a complete list is probably more useful and convenient than having a list of pairs which doesn't even include all pairs. For example the accepted solution does not list (11, 14), (12,14), etc. as pairs.

카테고리

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