필터 지우기
필터 지우기

Sum subarrays of a Matrix.

조회 수: 15 (최근 30일)
Santos García Rosado
Santos García Rosado 2021년 2월 25일
편집: Matt J 2021년 2월 26일
Hi Mathworks community! Could someone give me a hand?
I'm having trouble trying to sum parts of the arrays of a matrix. Let's say I have the following matrix A of r rows and c columns (rxc).
A = [1,2,3,4,5,6,7,8,9; 10,11,12,13,14,15,16,17,18; 19,20,21,22,23,24,25,26,27]
And what I would like to to is to divide each array in n subarrays (n=3) and sum each of those subarrays. In this case, it would be the sum of every three positions. Getting an output suchs as:
out = [5,15,24; 33,42,51; 60,69,78]
Thank's for the help!
Santos

채택된 답변

Fangjun Jiang
Fangjun Jiang 2021년 2월 25일
편집: Fangjun Jiang 2021년 2월 25일
One-liner
transpose(reshape(sum(reshape(A',3,[])),3,[]))
Or
transpose(cell2mat(cellfun(@sum,mat2cell(A',[3,3,3],3),'unif',0)))
  댓글 수: 2
Fangjun Jiang
Fangjun Jiang 2021년 2월 25일
Can this task be done using accumarray()?? accumarray always makes my head spin!
Santos García Rosado
Santos García Rosado 2021년 2월 26일
I'm using this code for Simulink and the first answer your proposea works perfectly fine. However, Simulink seems not to like the function cell2mat you wrote on the second line but it does work okay with Matlab. Thank's for the help Fangjun!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Matt J
Matt J 2021년 2월 25일
편집: Matt J 2021년 2월 26일
  댓글 수: 1
Santos García Rosado
Santos García Rosado 2021년 2월 26일
Nice function! I'm saving it for the future! Thanks Matt!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by