Sorting from the maximum value to minimum value in a vector

80 次查看(过去 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
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