Sort elements of an array with a given a priority, keeping track of indexes (includes repeated elements)
조회 수: 4 (최근 30일)
이전 댓글 표시
Hi,
I would like to sort an array vR = [1.5 2 1.25 3 3.5 5 8 2.359 3] with the following rules:
- Sorted integers
- Sorted half integers
- Sorted quarter integers
- Remaining sorted elements
After the sort is completed, I want to know the indexes of elements in the new array relative to the previous unsorted array.
Note: there can be repeated elements
vR_sorted = [2 3 3 5 8 1.5 3.5 1.25 2.359]
idxs = [2 4 9 6 7 1 5 3 8]
Thanks
댓글 수: 0
답변 (2개)
Stephen23
2019년 1월 22일
편집: Stephen23
2019년 1월 22일
>> vR = [1.5,2,1.25,3,3.5,5,8,2.359,3]
vR =
1.5000 2.0000 1.2500 3.0000 3.5000 5.0000 8.0000 2.3590 3.0000
>> [~,idx] = sortrows([bsxfun(@mod,vR(:),[1,0.5,0.25])~=0,vR(:)])
idx =
2
4
9
6
7
1
5
3
8
>> vS = vR(idx)
vS =
2.0000 3.0000 3.0000 5.0000 8.0000 1.5000 3.5000 1.2500 2.3590
For MATLAB versions R2016b and later bsxfun is not required:
[~,idx] = sortrows([mod(vR(:),[1,0.5,0.25])~=0,vR(:)])
댓글 수: 0
Kevin Phung
2019년 1월 22일
There might be something more elegant than my for-loop, but this should work. Let me know!
vR = [1.5 2 1.25 3 3.5 5 8 2.359 3 ];
integers = vR(floor(vR) ==vR); % rule 1
a = vR(not(ismember(vR,integers))); %NOT integers
half_int = a(floor(a - .5) == a-.5); %half integers
b = a(not(ismember(a,half_int))); % NOT half integers
list1 = b(floor(b - .25) == b-.25);
list2 = b(floor(b-.75) == b-.75);
quarter_int = [list1 list2];
leftOvr = b(not(ismember(b,quarter_int))); % remaining
sorted_vR = [sort(integers) sort(half_int) sort(quarter_int) leftOvr];
idx =[];
for i = 1 :numel(vR)
if any(ismember(vR,sorted_vR(i)))
idx1 = find(ismember(vR,sorted_vR(i)));
idx = [idx idx1]; % this will add in duplicates
end
end
idx = unique(idx,'stable'); % remove duplicate indices
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!