sum over a matrix with condition in matlab
assume I have a 10x10 matrix M
M=[64 36 50 87 22 45 37 23 68 88;
33 23 87 49 54 25 35 98 78 52;
12 54 76 43 24 87 54 98 45 34;
77 87 23 45 34 65 23 76 12 76;
12 34 55 44 76 98 93 23 54 67;
22 55 78 90 88 56 34 23 12 76;
99 23 67 89 34 23 12 87 45 23;
22 54 76 89 65 23 45 12 93 12;
44 56 23 88 67 14 15 67 34 12;
11 44 77 99 34 23 78 34 12 79];
- I want to first find out the local maximum in the matrix
- and then accordi开发者_运维百科ng to the maximum position do a sum over a 3x3 region over M
For the first step, the code I used is local_max=imregionalmax(M)
. to find out the local maximum position, but how can I go further to use this coordination to sum over a 3x3 matrix over M?
Thanks for the help.
You can calculate the sum for the whole matrix and then only keep the values that you're interested in. This should work:
local_max=imregionalmax(M)
sums = imfilter(M, ones(3));
local_max_sums = sums(local_max);
And if what you want is a matrix with non-zero entries where the local maxima are located:
local_max_sums = sums .* local_max;
You seem to be looking for the matrix subset functionality of Matlab.
Basically, for
M = [ 1 2 3 4 5 6;
4 5 6 7 8 9;
7 8 9 0 1 2;
0 1 2 3 4 5;
3 4 5 6 7 8;
6 7 8 9 0 1];
If you have a max at (3,3), you can use M(2:4, 2:4) to get
N = [ 5 6 7;
8 9 0;
1 2 3];
Summing that matrix is all that remains - as simple as
total = sum(N(:));
This is kind of brute force for Matlab, but I think it works.
bw = imregionalmax(M);
[x,y] = find(bw);
s = [];
for i = 1:length(x)
startX = x(i)-2;
if(startX < 1)
startX = 1;
end
endX = x(i)+2;
if endX > 10
endX = 10;
end
startY = y(i)-2;
if startY < 1
startY = 1;
end
endY = y(i)+2;
if endY > 10
endY = 10;
end
s(i) = sum2(M(startX:endX, startY:endY));
end
精彩评论