Sort values in a cell array

조회 수: 3 (최근 30일)
Sergio Rojas Blanco
Sergio Rojas Blanco 2022년 7월 21일
편집: Bruno Luong 2022년 7월 21일
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 :)

채택된 답변

Stephen23
Stephen23 2022년 7월 21일
편집: Stephen23 2022년 7월 21일
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
Sergio Rojas Blanco
Sergio Rojas Blanco 2022년 7월 21일
Stephen23, thank you very much. How fast!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Bruno Luong
Bruno Luong 2022년 7월 21일
편집: Bruno Luong 2022년 7월 21일
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]}

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by