grouping data in column vector based on another vector

2 次查看(过去 30 天)
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 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by