Using MorphologicalComponents
with ComponentMeasurements
:
ClearAll[counts]
counts[m_] := # /. ComponentMeasurements[#, "Count"] & @
MorphologicalComponents[m, CornerNeighbors -> False]
Using Carl's example array:
SeedRandom[0]
m = RandomInteger[1, {10, 10}];
m // MatrixForm // TeXForm
$\left(
\begin{array}{cccccccccc}
1 & 0 & 1 & 0 & 0 & 1 & 1 & 1 & 0 & 0 \\
0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
0 & 0 & 0 & 1 & 0 & 1 & 0 & 1 & 1 & 0 \\
0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 & 0 & 0 \\
1 & 1 & 1 & 1 & 0 & 1 & 1 & 0 & 0 & 1 \\
1 & 1 & 1 & 0 & 1 & 0 & 0 & 0 & 1 & 0 \\
0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 1 & 1 \\
1 & 0 & 0 & 1 & 1 & 0 & 0 & 0 & 0 & 1 \\
1 & 1 & 0 & 0 & 0 & 0 & 1 & 0 & 1 & 0 \\
1 & 0 & 1 & 0 & 1 & 0 & 1 & 1 & 0 & 0 \\
\end{array}
\right)$
counts[m][[3, 4]]
15
counts[m][[3, 2]]
0
counts @ m // MatrixForm // TeXForm
$ \left(
\begin{array}{cccccccccc}
1 & 0 & 2 & 0 & 0 & 3 & 3 & 3 & 0 & 0 \\
0 & 0 & 2 & 0 & 0 & 0 & 0 & 0 & 3 & 0 \\
0 & 0 & 0 & 15 & 0 & 15 & 0 & 3 & 3 & 0 \\
0 & 0 & 15 & 15 & 15 & 15 & 0 & 0 & 0 & 0 \\
15 & 15 & 15 & 15 & 0 & 15 & 15 & 0 & 0 & 1 \\
15 & 15 & 15 & 0 & 1 & 0 & 0 & 0 & 4 & 0 \\
0 & 0 & 0 & 3 & 0 & 0 & 0 & 0 & 4 & 4 \\
4 & 0 & 0 & 3 & 3 & 0 & 0 & 0 & 0 & 4 \\
4 & 4 & 0 & 0 & 0 & 0 & 3 & 0 & 1 & 0 \\
4 & 0 & 1 & 0 & 1 & 0 & 3 & 3 & 0 & 0 \\
\end{array}
\right)$
cnts = Union[Join @@ counts[m]];
Row[{MatrixPlot[m, ImageSize -> 250,
ColorFunction -> "Rainbow", ColorFunctionScaling -> False,
PlotLegends -> SwatchLegend["Rainbow", {0, 1}] ],
MatrixPlot[counts @ m, ImageSize -> 250,
ColorFunction -> ColorData[{"Rainbow", {0, Max[cnts]}}],
ColorFunctionScaling -> False,
PlotLegends -> SwatchLegend[ColorData["Rainbow"]/@Rescale[cnts], cnts] ]},
Spacer[10]]

g[x_] := 2 g[x-1]
, together with appropriate starting values). You may also useNest
,Fold
, etc. $\endgroup$