How can I sum the rows of a matrix at a fixed distance between each other?

3 ビュー (過去 30 日間)
MRC
MRC 2013 年 12 月 2 日
回答済み: Wayne King 2013 年 12 月 2 日
Hi, I have a vector A (m*p)x1 and I want to create a vector B px1 where B(i)=sum_{n=0}^{m-1}A(i+p*n), e.g.
m=3;
p=4;
A=[12;11;10;9;8;7;6;5;4;3;2;1];
B=[A(1)+A(5)+A(9);A(2)+A(6)+A(10);A(3)+A(7)+A(11);A(4)+A(8)+A(12)];
I can't use loops.

採用された回答

Sean de Wolski
Sean de Wolski 2013 年 12 月 2 日
Use reshape and sum along a specific dimension:
m=3;
p=4;
A=[12;11;10;9;8;7;6;5;4;3;2;1];
B=[A(1)+A(5)+A(9);A(2)+A(6)+A(10);A(3)+A(7)+A(11);A(4)+A(8)+A(12)];
C=sum(reshape(A,p,m),2);
assert(isequal(B,C));

その他の回答 (1 件)

Wayne King
Wayne King 2013 年 12 月 2 日
A = reshape(A,4,3);
sum(A,2)

カテゴリ

Help Center および 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