# Sort values in a cell array

1 view (last 30 days)
Sergio Rojas Blanco on 21 Jul 2022
Edited: Bruno Luong on 21 Jul 2022
Hi guys, It's amazing how much some people know.
Well, this is my case:
I have a vector. Suppose this:
A=[90,45,38,51];
To this vector correspond another vector. Some values may be duplicates but it is not known how many.
B=[8,1,8,3]
So, I want to sort them and set the initial values in a cell array. The result would be this:
C={[45],[51],[90,38] }
I wish I didn't have to use loop.
Thank you all for your help, especially helping me with this :)
##### 0 CommentsShow -2 older commentsHide -2 older comments

Sign in to comment.

### Accepted Answer

Stephen23 on 21 Jul 2022
Edited: Stephen23 on 21 Jul 2022
A = [90,45,38,51];
B = [8,1,8,3];
[~,~,X] = unique(B);
C = accumarray(X,A(:),[],@(v){v})
C = 3×1 cell array
{[ 45]} {[ 51]} {2×1 double}
Checking the content of C:
C{:}
ans = 45
ans = 51
ans = 2×1
90 38
##### 1 CommentShow -1 older commentsHide -1 older comments
Sergio Rojas Blanco on 21 Jul 2022
Stephen23, thank you very much. How fast!

Sign in to comment.

### More Answers (1)

Bruno Luong on 21 Jul 2022
Edited: Bruno Luong on 21 Jul 2022
Another method
B=[8,1,8,3];
A=[90,45,38,51];
[Bs,i]=sort(B);
mat2cell(A(i),1,diff(find([true,diff(Bs)>0,true])))
ans = 1×3 cell array
{[45]} {[51]} {[90 38]}
% or more compact
mat2cell(A(i),1,diff(find([1,diff(Bs),1])))
ans = 1×3 cell array
{[45]} {[51]} {[90 38]}
##### 1 CommentShow -1 older commentsHide -1 older comments
Sergio Rojas Blanco on 21 Jul 2022
Bruno Luong, very good. Thank you

Sign in to comment.

### Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

R2021b

### Community Treasure Hunt

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

Start Hunting!