MATLAB: How to calculate the mean of the elements values of the array according to objects of the other array.

arraysfindImage Processing Toolboxmeanobject

Imagine that i have two arrays:
A = [3 3 3 3 1 1 1 1 1 1 8 8;
3 3 3 5 1 1 1 1 1 8 8 8;
3 3 3 5 5 1 1 1 8 8 8 8;
3 3 3 5 5 5 1 8 8 8 8 8;
7 7 7 5 5 5 6 6 6 8 8 8;
7 7 7 5 5 5 6 6 6 4 4 4;
7 7 2 2 2 6 6 6 6 4 4 4;
7 2 2 2 2 6 6 6 6 4 4 4;
2 2 2 2 2 2 6 6 4 4 4 4]
B = [5 4 4 3 7 5 8 8 7 9 4 8;
6 8 9 4 2 3 6 7 7 7 6 8;
7 2 4 7 7 9 4 2 4 8 8 9;
8 2 4 2 6 5 2 8 1 1 7 9;
4 8 2 8 8 3 2 2 6 2 5 8;
1 1 3 1 6 4 5 6 2 7 3 1;
7 7 3 5 9 7 4 5 7 7 7 1;
3 7 9 1 4 4 7 2 5 7 4 1;
8 4 3 7 4 2 1 1 3 5 6 3]
I want ans like this :
C = [5,07 5,07 5,07 5,07 5,73 5,73 5,73 5,73 5,73 5,73 6,05 6,05;
5,07 5,07 5,07 5,08 5,73 5,73 5,73 5,73 5,73 6,05 6,05 6,05;
5,07 5,07 5,07 5,08 5,08 5,73 5,73 5,73 6,05 6,05 6,05 6,05;
5,07 5,07 5,07 5,08 5,08 5,08 5,73 6,05 6,05 6,05 6,05 6,05;
4 4 4 5,08 5,08 5,08 4,12 4,12 4,12 6,05 6,05 6,05;
4 4 4 5,08 5,08 5,08 4,12 4,12 4,12 4,23 4,23 4,23;
4 4 5,07 5,07 5,07 4,12 4,12 4,12 4,12 4,23 4,23 4,23;
4 5,07 5,07 5,07 5,07 4,12 4,12 4,12 4,12 4,23 4,23 4,23;
5,07 5,07 5,07 5,07 5,07 5,07 4,12 4,12 4,23 4,23 4,23 4,23]
The figure may explain better.

Best Answer

A is your labeled matrix. B is your intensity matrix. Use regionprops() (in the Image Processing Toolbox) and ask for MeanIntensity:
A = [3 3 3 3 1 1 1 1 1 1 8 8;
3 3 3 5 1 1 1 1 1 8 8 8;
3 3 3 5 5 1 1 1 8 8 8 8;
3 3 3 5 5 5 1 8 8 8 8 8;
7 7 7 5 5 5 6 6 6 8 8 8;
7 7 7 5 5 5 6 6 6 4 4 4;
7 7 2 2 2 6 6 6 6 4 4 4;
7 2 2 2 2 6 6 6 6 4 4 4;
2 2 2 2 2 2 6 6 4 4 4 4]
B = [5 4 4 3 7 5 8 8 7 9 4 8;
6 8 9 4 2 3 6 7 7 7 6 8;
7 2 4 7 7 9 4 2 4 8 8 9;
8 2 4 2 6 5 2 8 1 1 7 9;
4 8 2 8 8 3 2 2 6 2 5 8;
1 1 3 1 6 4 5 6 2 7 3 1;
7 7 3 5 9 7 4 5 7 7 7 1;
3 7 9 1 4 4 7 2 5 7 4 1;
8 4 3 7 4 2 1 1 3 5 6 3]
props = regionprops(A, B, 'MeanIntensity')
allIntensities = [props.MeanIntensity]
C = zeros(size(A))
for k = 1 : max(A(:))
C(A==k) = allIntensities(k);
end
C % Print to command window.