필터 지우기
필터 지우기

Working with cell arrays

조회 수: 4 (최근 30일)
L'O.G.
L'O.G. 2023년 5월 5일
댓글: Stephen23 2023년 5월 8일
I would like to separate columns in an array based on the unique values of the first column. I think the way to do this is a cell array since the vectors would be of different length. Is there a way to vectorize this? For example, the following array
example = [
5 2.3 1.7
5 0.2 9.1
99 3.3 3.6
99 4.1 3.2
99 5.1 2.2
103 1.1 6.8
];
should give
A{1} = [2.3,0.2];
A{2} = [3.3,4.1,5.1];
A{3} = [1.1];
B{1} = [1.7,9.1];
B{2} = [3.6,3.2,2.2];
B{3} = [6.8];
(since there are three unique values in column 1 of the example)

채택된 답변

Paul
Paul 2023년 5월 5일
example = [
5 2.3 1.7
5 0.2 9.1
99 3.3 3.6
99 4.1 3.2
99 5.1 2.2
103 1.1 6.8
];
G = findgroups(example(:,1));
A = splitapply(@(x) mat2cell(x,numel(x)),example(:,2),G);
B = splitapply(@(x) mat2cell(x,numel(x)),example(:,3),G);
A,B
A = 3×1 cell array
{2×1 double} {3×1 double} {[ 1.1000]}
B = 3×1 cell array
{2×1 double} {3×1 double} {[ 6.8000]}
A{1}
ans = 2×1
2.3000 0.2000
B{1}
ans = 2×1
1.7000 9.1000
  댓글 수: 1
Stephen23
Stephen23 2023년 5월 8일
Also without the MAT2CELL call:
X = [
5 2.3 1.7
5 0.2 9.1
99 3.3 3.6
99 4.1 3.2
99 5.1 2.2
103 1.1 6.8
];
G = findgroups(X(:,1));
A = accumarray(G,X(:,2),[],@(a){a});
B = accumarray(G,X(:,3),[],@(a){a});
A,B
A = 3×1 cell array
{2×1 double} {3×1 double} {[ 1.1000]}
B = 3×1 cell array
{2×1 double} {3×1 double} {[ 6.8000]}
A{1}
ans = 2×1
2.3000 0.2000
B{1}
ans = 2×1
1.7000 9.1000

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by