grouping data in column vector based on another vector

9 ビュー (過去 30 日間)
Pooneh Shah Malekpoor
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 Center および File ExchangeData Type Identification についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by