grouping data in column vector based on another vector

조회 수: 9 (최근 30일)
Pooneh Shah Malekpoor
Pooneh Shah Malekpoor 2021년 5월 14일
댓글: Pooneh Shah Malekpoor 2021년 5월 14일
Hello
I have a column vector A as [0;1;2;3;4]. On the other hand, there is another column vector called C=[15;16 ;17; 18; 20;19;7;8;22;25].
I want to group data in matrix C based on arrays in A such that A(1)=0 then nothing is selected from C so C(1)=0. Then as A(2)=1, so the first array from C is selected so C(2)=15. Then as A(3)=2 so two arrays from C are selected so 16 and 17 are grouped together as C(3)=[16,17]. Then as A(4)=3, so C(4)=[18,20,19]. And finally, A(5)=4 so C(5)=7,8,22,25].
Any idea is highly appreciated.
Bests

채택된 답변

KSSV
KSSV 2021년 5월 14일
A = [0; 1; 2; 3; 4] ;
B = [15;16 ;17; 18; 20;19;7;8;22;25] ;
N = length(A) ;
C = cell(N,1) ;
for i = 1:N
if A(i) == 0
C{i} = 0 ;
else
C{i} = B(1:A(i)) ;
B(1:A(i)) = [] ;
end
end
celldisp(C)
C{1} = 0 C{2} = 15 C{3} = 16 17 C{4} = 18 20 19 C{5} = 7 8 22 25

추가 답변 (1개)

Dyuman Joshi
Dyuman Joshi 2021년 5월 14일
편집: Dyuman Joshi 2021년 5월 14일
Assuming that sum(A) == numel(C), You can use for loops and cell arrays to get the result
X=C; %Assigning C to another variable in case you need C again
for i=1:numel(A)
if A(i)==0
Y{i}=0;
else
Y{i} = X(1:A(i))';
end
X(1:A(i))=[];
end
Y = 1×5 cell array
{[0]} {[15]} {[16 17]} {[18 20 19]} {[7 8 22 25]}
P.S - This might not be the most efficient method. There was a similar Cody question, if I find a better solution, I will update it here.

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by