Blockwise matrix addition without using more than 2 dimensions and cycles

2 ビュー (過去 30 日間)
Bence Cseppento
Bence Cseppento 2022 年 11 月 21 日
コメント済み: Bence Cseppento 2022 年 11 月 23 日
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.

採用された回答

the cyclist
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)
B = 2×4
6 8 10 12 22 24 26 28
  1 件のコメント
Bence Cseppento
Bence Cseppento 2022 年 11 月 23 日
Thanks for your effort, it does look good but I'll have to test it for some other cases.
In the mean time I managed to solve my problem by managing a conversion between types and using the original 3D version, but I did not know about the movsum() function before so you have given me food for thought, thank you!

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

その他の回答 (1 件)

the cyclist
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)
B = 2×4
6 8 10 12 22 24 26 28
  1 件のコメント
Bence Cseppento
Bence Cseppento 2022 年 11 月 21 日
Thank you, I was a bit over-complicating it because of the context of my problem which I have not shared. However, I am still looking for a more general solution, e.g. I want to get a 2x20 matrix from a 2x2000 matrix, by summing the (:,1:20), (:,21:40) ... (:,1981:2000) submatrices without the use of a cycle.

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

カテゴリ

Help Center および File ExchangeFunction Creation についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by