How to aggregate data based on values in a vector?

I have matrix A containing 128 columns and m rows. I want to aggregate columns in matrix A based on values in a vector B containing n columns. In the instance that:
A = rand(1000,128);
B = [32 45 58 62 73 84 103 112];
I would want to sum columns 1:32 33:45 46:58 59:62 63:73 74:84 85:103 104:112 and 113:128 of matrix A to create a new 1000x9 matrix C. Right now, my code to perform this process is:
C = horzcat(...
sum(A(:,1:B(1)),2),...
sum(A(:,B(1)+1:B(2)),2),...
sum(A(:,B(2)+1:B(3)),2),...
sum(A(:,B(3)+1:B(4)),2),...
sum(A(:,B(4)+1:B(5)),2),...
sum(A(:,B(5)+1:B(6)),2),...
sum(A(:,B(6)+1:B(7)),2),...
sum(A(:,B(7)+1:B(8)),2),...
sum(A(:,B(8)+1:end),2));
I would like to automate this process so that I can change the number of columns in vector B without altering my aggregation code
Many thanks!

 採用された回答

Jos (10584)
Jos (10584) 2017 年 12 月 14 日
編集済み: Jos (10584) 2017 年 12 月 14 日

0 投票

Here is one flexible approach:
A = cumsum(ones(3,10),2) % a simple example, easy to check
B = [2 5 6]
B2 = [0 B size(A,2)]
C = arrayfun(@(k) sum(A(:,(B2(k)+1):B2(k+1)),2), 1:numel(B2)-1,'un',0)
C = cat(2,C{:})

2 件のコメント

HeadInTheClouds
HeadInTheClouds 2017 年 12 月 15 日
This works great! Thank you!
Lateef Adewale Kareem
Lateef Adewale Kareem 2019 年 4 月 7 日
編集済み: Lateef Adewale Kareem 2019 年 4 月 7 日
Another way to look at it is to define starting and ending B(s)
B1 = [1,B+1]; B2 = [B,size(A,2)];
C = arrayfun(@(k1,k2)sum(A(:,k1:k2),2),B1,B2,'un',0);
C = cat(2,C{:})

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by