separate matrix into cells according to column value

조회 수: 2 (최근 30일)
Alejandro Fernández
Alejandro Fernández 2020년 8월 30일
댓글: Alejandro Fernández 2020년 8월 30일
Hi, I have a matrix like the one I show in A:
A = [1 2 1; 2 2 1; 1 2 2; 2 2 3];
What I intend to achieve in each component of cell B is the first and second column of matrix A whose component index corresponds to the value of the third column of A.
B{1} = [1 2; 2 2];
B{2} = [1 2];
B{3} = [2 2];
I can do it with the next code but I am looking for a better and faster method because i usually have a lot of cell components.
for i = 1 : 3
B{i} = A(A(:,3) == i,1:2);
end

채택된 답변

Bruno Luong
Bruno Luong 2020년 8월 30일
One liner (not the fatest)
B = splitapply(@(x) {x}, A(:,1:2), A(:,3))
  댓글 수: 1
Alejandro Fernández
Alejandro Fernández 2020년 8월 30일
In my case is faster than my so it's perfect! thank you!!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Types에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by