grouping data in column vector based on another vector

10 vues (au cours des 30 derniers jours)
Pooneh Shah Malekpoor
Pooneh Shah Malekpoor le 14 Mai 2021
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

Réponse acceptée

KSSV
KSSV le 14 Mai 2021
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

Plus de réponses (1)

Dyuman Joshi
Dyuman Joshi le 14 Mai 2021
Modifié(e) : Dyuman Joshi le 14 Mai 2021
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.

Catégories

En savoir plus sur Data Type Identification dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by