Sort cell values greater and smaller than the threshold

9 views (last 30 days)
I have
C={[7],[4],[1],[2],[1],[3]};
A = [1 2 4 9; 6 9 9 13; 9 14 9 15; 11 14 11 14; 13 14 15 18; 11 16 11 16];
thresh = 3;
I want to sort the cell array according to
1-find values bigger than 3
{[7],[4],[3]}
2- sort it from smallest (3) to largest
{[3],[4],[7]}
3- add the remaining value of C to C_new (in largest to smallest order)
C_new ={[3],[4],[7],[2],[1],[1]}
4- change the order of A according to C_new
[7] in C is correspond to [1 2 4 9] in A
result should be
C_new ={[3],[4],[7],[2],[1],[1]}
A_new = [ 11 16 11 16;
6 9 9 13;
1 2 4 9;
11 14 11 14;
9 14 9 15;
13 14 15 18]

Accepted Answer

the cyclist
the cyclist on 10 Apr 2020
Edited: the cyclist on 10 Apr 2020
A little awkward, but it works.
The algorithm is based on the fact that you want all elements sorted by their distance from the threshold value, but with all the above-threshold values coming before the below-threshold values.
% Original data
C={[7],[4],[1],[2],[1],[3]};
A = [1 2 4 9; 6 9 9 13; 9 14 9 15; 11 14 11 14; 13 14 15 18; 11 16 11 16];
thresh = 3;
% Convert C to numeric
dblC = cell2mat(C);
% Find the maximum distance that any element is from threshold.
% (This will become a "penalty" to below-threshold values,
% ensuring they are "further" from the threshold than any
% above-threshold value
maxdist = max(abs(dblC-thresh));
% Define a metric that is distance from threshold,
% but where below-threshold values are penalized
metric = abs(dblC-thresh) + maxdist.*(dblC<thresh);
% Sort the values according to that metric
[~,sortingIndex] = sort(metric);
C_new = C(sortingIndex);
A_new = A(sortingIndex,:);

More Answers (1)

Image Analyst
Image Analyst on 10 Apr 2020
Clear as mud. I have no idea what A is used for, what step 4 means, and how A_new is computed, but this will get you through step 3:
C={[7],[4],[1],[2],[1],[3]}
dblC = cell2mat(C) % Convert to double for simplicity in sorting.
A = [1 2 4 9; 6 9 9 13; 9 14 9 15; 11 14 11 14; 13 14 15 18; 11 16 11 16]
thresh = 3;
logicalIndexes = dblC >= thresh
part1 = sort(dblC(logicalIndexes), 'ascend')
part2 = sort(dblC(~logicalIndexes), 'descend')
cMat = [part1, part2]
% Put into cell for some weird reason
for k = 1 : length(cMat)
C_new{k} = cMat(k);
end
Though it baffles me why C and C_new are cell arrays in the first place instead of much simpler double vectors.

Community Treasure Hunt

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

Start Hunting!