Sum matrix column orderly

9 views (last 30 days)
christine QQ
christine QQ on 30 Nov 2021
Edited: Matt J on 30 Nov 2021
Dear all, I have a matrix A(1022*100) now. I want to make a matrix B, which column will be follow by these rules: (1) Matrix B column 1 will be sum (1-15)column in matrix A. (2)B column 2 will be sum (2-16)column in matrix A.etc. Examples: matrix example_matrix[1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16] ,sum 3 matrix columns orderly and put all the answers in to new matrix. (Answers_matrix column 1:[1+5+9,2+6+10,3+7+11,4+8+12] column 2:[5+9+13,6+10+14,7+11+15,8+12+16])Final_matrix:[15,18,21,24;27,30,33,36] thank you for your help!! I am appreciate it!!

Answers (3)

Benjamin
Benjamin on 30 Nov 2021
This will work for your example_matrix:
Final_matrix = movsum(example_matrix,3,1,'Endpoints','discard');
Maybe doing the same but with 15-point moving sum instead of 3-point is what you have in mind for the matrix A.

Awais Saeed
Awais Saeed on 30 Nov 2021
Edited: Awais Saeed on 30 Nov 2021
chnage first_row and end_row according to your requirement
A = [1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16]
A = 4×4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
start_row = 1;
end_row = 3;
for row = 1:1:size(A,1)
for col = 1:1:size(A,2)
M(row,col) = sum(A(start_row:end_row,col));
end
start_row = start_row + 1;
end_row = end_row + 1;
if (end_row > size(A,2))
break;
end
end
disp(M)
15 18 21 24 27 30 33 36

Matt J
Matt J on 30 Nov 2021
Edited: Matt J on 30 Nov 2021
B=conv2(A,ones(15,1),'valid').';

Community Treasure Hunt

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

Start Hunting!

Translated by