double summation of a matrix
7 views (last 30 days)
Show older comments
can anyone help me perform this summation in matlab? S is a 330X332 uint8 matrix.
i tried with 2 for loops but it doesnt work.
thank you!
2 Comments
Accepted Answer
John D'Errico
on 5 May 2020
Edited: John D'Errico
on 5 May 2020
Of course it does work to use loops. Therefore, your loops were not written correctly. :-) However, it is far easier to write the entire process in one simple line of code.
U = conv2(double(S),ones(5))/25;
Note that I converted S using the double command, since you will divide by 25 at the end. Anyway, forming that sum would have likely caused uint8 overflows if you did it inside loops, unless you were careful to avoid them.
However, there is likely a problem in this result, since you have not told us what to do around the boundaries of the matrix. What is shown above will produce a new matrix that is size 334X336, so 4 rows and 4 columns larger. Why?
The answer is what would you compute whem m=n=1? conv2 makes the assumption that around the borders, it implicitly expands your matrix with zeros as necessary. But this means the sum around the borders will look strange. So I would predict you will not be happy, because around the borders, you will be forming a sum of less than 25 elements, yet you will be always dividing by 25.
So, instead, I would suggest you decide exactly what to do around the perimeter. This would probably be described as the boundary conditions for this operation.
If I had to guess what you most likely want to do, it is this:
U = conv2(double(S),ones(5),'same') ./ conv2(ones(size(S)),ones(5),'same');
I'll allow you to figure out why this operation works, even around the perimeter of the array, forming the desired average of elements. Perhaps this small example will help:
conv2(ones(7),ones(5),'same')
ans =
9 12 15 15 15 12 9
12 16 20 20 20 16 12
15 20 25 25 25 20 15
15 20 25 25 25 20 15
15 20 25 25 25 20 15
12 16 20 20 20 16 12
9 12 15 15 15 12 9
The resulting matrix in U will be the same size and shape as S. If you want the result to be essentially another image (as I assume this is what you are working on), stored back into uint8, you could then convert it back into uint8.
U = uint8(U);
More Answers (2)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!