sum the matrix 3x3 and looping

how to calculate the total of overlap region 3x3 of a matrix and include loop function as it continue to calculate row by row and column by column.

2 Comments

the cyclist
the cyclist on 28 Feb 2014
Edited: the cyclist on 28 Feb 2014
This is not even close to detailed enough to help you. For starters, what does "overlap region" mean?
Please remember, we only know what you tell us about your problem.
sorry, it suppose to be like this. i have the code to calculate the sum for the matrix, but dun't know how to do the looping part.
t=rand(6,6)
total = 0;
for i=1:3
for j=1:3
total = total + t(i,j)
end
end

Sign in to comment.

 Accepted Answer

That can be done very simply with imfilter() or conv2():
outputArray = conv2(double(inputArray), ones(3), 'same');
Every element (pixel) in the output array (image) will be the sum of input elements (pixels) in the sliding window.

7 Comments

i dun't really understand how to use conv2() please help me.
conv2 multiplies each value of the sliding window mask (array, or "kernel") by the value of the larger image that it is over, and then sums up all 9 products. So if the kernel is all 1's then it multiples the image under the kernal by all 1's and sums them up. This is simply the sum, which is what you wanted, right? Then it just slides the window over every pixel in the image (or element in the array) so the output image is simply the sum of the input image inside the window when the window is over that element. You said you need to calculate the sum, so do you now see how that calculates the sum? If not, then explain how you would do it. After you do that, you'll see you just described what conv2 does.
can i get the full coding. I'm new to matlab.
I gave you the full coding. That was it. I assume you already have some kind of matrix. So just replace "inputArray" with the name of your matrix. That's it - you're done. If you still need an example, see the attached.
Thanks. Can you help with this I have a 3x3 array inside this entire 200x200 matrix and produce a new array.
For example,
x = [1 2 3 4;5 6 7 8;9 10 11 12;13 14 15 16]
I want sum of [1 2 3;5 6 7;9 10 11] which is = 54. and [2 3 4;6 7 8;10 11 12] = 63, and [5 6 7;9 10 11;13 14 15] = 19. and so on. Then store these values into a new array. Which is z = [54 63 90] Please help, thank you
x = [1 2 3 4;5 6 7 8;9 10 11 12;13 14 15 16]
theSums = conv2(x, ones(3), 'valid')
Result:
theSums =
54 63
90 99
As you can see, you forgot one sum. Please mark the answer as Accepted if we're done here. Thanks.
thank you very much.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 28 Feb 2014

Edited:

on 2 Mar 2014

Community Treasure Hunt

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

Start Hunting!