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
0 个评论
采纳的回答
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)
更多回答(1 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!