how to sort a cell array based on another cell array

basically i have this cell array:
A = {1,18,2,1,6,8,3,1,1,1}
B = {the,keep,up,run,a,fear,have,tik,love,vik}
basically each element in B have the number of occurances in A, what i need to do is i want to sort A in descendant order ( 18,8,6...) but also i want its corresponding B to sort with it how can i achieve that ?

 Accepted Answer

So 'the' has 1 occurrence, 'keep' has 18 occurrences, 'up' has 2 occurrences, and so on.
Exactly where ARE these occurrences? You did not show any array with those number of occurrences.
So anyway, let's assume A is really a double array instead of a cell array and you want to sort B with the same sort order as A, you'd do this:
A = [1,18,2,1,6,8,3,1,1,1]
B = {'the','keep','up','run','a','fear','have','tik','love','vik'}
[sortedA, sortOrder] = sort(A, 'descend')
B = B(sortOrder)
You'll see
sortedA =
18 8 6 3 2 1 1 1 1 1
sortOrder =
2 6 5 7 3 1 4 8 9 10
B =
1×10 cell array
{'keep'} {'fear'} {'a'} {'have'} {'up'} {'the'} {'run'} {'tik'} {'love'} {'vik'}

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!