Blockwise matrix addition without using more than 2 dimensions and cycles
조회 수: 2 (최근 30일)
이전 댓글 표시
Dear All,
I am looking for a solution of blockwise matrix addition. To give a simple example, let us have
A = [1,2,3,4,5,6,7,8; 9,10,11,12,13,14,15,16];
I would like to get the result:
B = [1+5,2+6,3+7,4+8; 9+13,10+14,11+15,12+16];
The evident solution which comes to mind would be:
sum(reshape(A,2,4,2), 3);
However, I am using a third-party tool with special variables for which 3D arrays are not implemented. My next idea was to use:
B = zeros(2,4);
for i = 1:4
B(:,i) = sum(A(:, i:4:end), 2);
end
If possible I am looking for functions that can solve this without using a cycle as in my application the number of columns will reach hundreds and thousands. I thank for in advance for anyone's help.
댓글 수: 0
채택된 답변
the cyclist
2022년 11월 22일
This is awkward, but it does what you want. I think there is probably a better way.
% Inputs
A = [1,2,3,4,5,6,7,8; 9,10,11,12,13,14,15,16];
groupSize = 4;
% Output
B = movsum(A,[0,groupSize],2) - movsum(A,[0,groupSize-1],2) + A;
B = B(:,1:groupSize)
추가 답변 (1개)
the cyclist
2022년 11월 21일
A = [1,2,3,4,5,6,7,8; 9,10,11,12,13,14,15,16];
B = A(:,1:end/2) + A(:,(end/2)+1:end)
참고 항목
카테고리
Help Center 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!