Re: Add terms surrounded by zero together in matrix
- To: mathgroup at smc.vnet.net
- Subject: [mg59150] Re: Add terms surrounded by zero together in matrix
- From: Peter Pein <petsie at dordos.net>
- Date: Sat, 30 Jul 2005 01:25:31 -0400 (EDT)
- References: <dcccur$3j7$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
mchangun at gmail.com schrieb:
> Hi All,
>
> I think this is a rather tough problem to solve. I'm stumped and would
> really appreciated it if someone can come up with a solution.
>
> What i want to do is this. Suppose i have the following matrix:
>
> 0 0 0 1 0
> 0 0 1 2 0
> 0 0 0 2 1
> 1 3 0 0 0
> 0 0 0 0 0
> 0 0 0 0 0
> 0 0 1 1 0
> 5 0 3 0 0
> 0 0 0 0 0
> 0 0 0 3 1
>
> I'd like to go through it and sum the elements which are surrounded by
> zeros. So for the above case, an output:
>
> [7 4 5 5 4]
>
> is required. The order in which the groups surrounded by zero is
> summed does not matter.
>
> The elements are always integers greater than 0.
>
> Thanks for any help!
>
slow, but working:
Clear[IslandSum];
IslandSum[m_] :=
Module[{pos = Position[m, _?Positive], r = {},
neighborQ = Max @@ Abs[#1 - #2] <= 1 & ,
neighbors, q, dq},
neighbors[l_, y_] := Pick[l, neighborQ[y, #1]& /@ l];
While[pos != {},
For[q = dq = {First[pos]}; pos = Rest[pos],
pos != {} != dq,
pos = Complement[pos, dq],
dq = Flatten[neighbors[pos, #1]& /@ dq, 1];
q = Join[q, dq]
];
AppendTo[r, Union[q]];
];
Plus @@@ Map[Extract[m, #1]& , r, {2}]
]
(* your example *)
mat =
{{0, 0, 0, 1, 0}, {0, 0, 1, 2, 0}, {0, 0, 0, 2, 1}, {1, 3, 0, 0, 0},
{0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 1, 1, 0}, {5, 0, 3, 0, 0},
{0, 0, 0, 0, 0}, {0, 0, 0, 3, 1}};
IslandSum[mat]
--> {7, 4, 5, 5, 4}
SeedRandom[19630724];
bigmat = Table[Boole[Random[] > 0.8], {100}, {50}];
First[Timing[
result = IslandSum[bigmat];]]
Length[result]
--> 6.359*Second
383
testmat = Table[Boole[Random[] > 0.8], {10}, {10}];
ListDensityPlot[Reverse[testmat]];
IslandSum[testmat]
--> [graphic omitted]
{4, 3, 1, 1, 1, 8, 3, 3, 1, 1}
--
Peter Pein
Berlin