Finding the sum of array
显示 更早的评论
What I'm trying to do is to find the sum of the surrounding elements of an binary array
For example
[1 0 0 1;
1 0 1 0;
0 0 1 1;
1 0 0 0]
would return
[1 3 2 1;
1 4 3 3;
2 4 2 2;
0 2 2 2]
but is there a way to do so without using conv2? as I dont really understand what conv2 does
采纳的回答
更多回答(2 个)
Image Analyst
2015-1-15
0 个投票
How about you just understand what conv2() does in that case. Basically it slides a window along and multiplies the window values (all 1's in the case where you want to do a sum) by the values of the larger matrix and then sums the products. So if they're all 1 except the middle is 0, it just multiplies the larger matrix by one and sums. So the value of the output at the pixel location is simply the sum of the original image matrix values, except for the center pixel itself, in a window centered around that pixel.
Image Analyst
2015-1-16
Timmy's code doesn't work because it's messed up and not robust. Here is a fixed version of his code that does work and is more robust (though it could be more robust/general because it assumes B must be a 3 by 3 matrix):
A = [1 0 0 1;
1 0 1 0;
0 0 1 1;
1 0 0 0]
B = [1 1 1;1 0 1;1 1 1]; % Code assumes this is a 3x3 matrix.
[rows, columns] = size(A);
A_prime = zeros(rows+2, columns+2);
A_prime(2:(1+rows),2:(1+columns)) = A;
theCounts = zeros(size(A_prime));
for col = 2 : size(A_prime, 2)-1
for row = 2 : size(A_prime, 1)-1
thisWindow = (A_prime(row-1:row+1,col-1:col+1) .* B) ~= 0;
theCounts(row,col) = sum(thisWindow(:));
end
end
theCounts = theCounts(2:end-1, 2:end-1)
In the command window
A =
1 0 0 1
1 0 1 0
0 0 1 1
1 0 0 0
theCounts =
1 3 2 1
1 4 3 4
2 4 2 2
0 2 2 2
类别
在 帮助中心 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!