Sum a matrix element using a window size of 4

조회 수: 2 (최근 30일)
Rahul Gulia
Rahul Gulia 2023년 6월 19일
댓글: Rahul Gulia 2023년 6월 21일
Hi everyone,
I am trying to create a matrix(4,2) from a matrix (4,8), by adding 4 elements column wise.
For example:
A = [-2 -2 -2 2 -2 2 -2 -2
-2 2 -2 -2 -2 -2 -2 2
-2 -2 2 -2 -2 2 2 2
-2 2 2 2 -2 -2 2 -2]
should be converted to:
B = [-4 -4
-4 -4
-4 4
4 -4 ]
Looking forward to any kind of suggestion. I was trying a for loop, but that is kind of messy for a large matrix. Hoping to get some simpler solutions by directly using the sum() function. Kindly sugest.

채택된 답변

Image Analyst
Image Analyst 2023년 6월 19일
Try blockproc if you have the Image Processing Toolbox:
A = [-2 -2 -2 2 -2 2 -2 -2
-2 2 -2 -2 -2 -2 -2 2
-2 -2 2 -2 -2 2 2 2
-2 2 2 2 -2 -2 2 -2]
A = 4×8
-2 -2 -2 2 -2 2 -2 -2 -2 2 -2 -2 -2 -2 -2 2 -2 -2 2 -2 -2 2 2 2 -2 2 2 2 -2 -2 2 -2
sumFunction = @(theBlockStructure) sum(theBlockStructure.data(:));
B = blockproc(A, [1, 4], sumFunction)
B = 4×2
-4 -4 -4 -4 -4 4 4 -4

추가 답변 (1개)

John D'Errico
John D'Errico 2023년 6월 19일
편집: John D'Errico 2023년 6월 19일
Reshape the array, to be now of size 4x4x2
A = [-2 -2 -2 2 -2 2 -2 -2
-2 2 -2 -2 -2 -2 -2 2
-2 -2 2 -2 -2 2 2 2
-2 2 2 2 -2 -2 2 -2];
Think about the result. What will it look like?
A2 = reshape(A,[4,4,2])
A2 =
A2(:,:,1) = -2 -2 -2 2 -2 2 -2 -2 -2 -2 2 -2 -2 2 2 2 A2(:,:,2) = -2 2 -2 -2 -2 -2 -2 2 -2 2 2 2 -2 -2 2 -2
Now, can you sum that new array, along the SECOND dimension? TRY IT!
A2sum = sum(A2,2)
A2sum =
A2sum(:,:,1) = -4 -4 -4 4 A2sum(:,:,2) = -4 -4 4 -4
Are you getting close? I hope so. Next, all you need to do is to get rid of that pesky second, singleton dimension. For that, you could use either reshape, or squeeze. TRY IT!
The trick in all of these problems is to understand the sequence in which the elements in your array are stored , and to then visualize what you want in the end. Work towards that goal.
  댓글 수: 1
Rahul Gulia
Rahul Gulia 2023년 6월 20일
Thank you for your suggestion @John D'Errico. That is an interesting way to look at the problem. I would surely apply that for smaller size matrices.

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by