
Add terms surrounded by zero together in matrix
Posted:
Jul 31, 2005 1:08 AM


I consider two nonzero elements that touch under 45 degrees as belonging to the same group. So e.g. starting with the 3x3 identity matrix results in {3} rather than {1,1,1}. If this is not what you want you can remove {1,1} and {1,1} from the following solution.
In[1]:= 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}};
In[2]:= pos = Position[mat, _?Positive]; Clear[h, g]; maxh = 0; h[{_, _}] = 0; g[x_] := x; tobejoined = {}; Do[m = Union[Select[h /@ (pos[[i]] + #1 & ) /@ {{1, 1}, {1, 0}, {1, 1}, {0, 1}}, Positive]]; If[m == {}, h[pos[[i]]] = maxh = maxh + 1, h[pos[[i]]] = m[[1]]; If[Length[m] > 1, AppendTo[tobejoined, m]]], {i, 1, Length[pos]}]; ((g[#1[[2]]] = #1[[1]]) & ) /@ tobejoined; Total /@ Map[mat[[#1[[1]],#1[[2]]]] & , Reap[Scan[Sow[#1, g[h[#1]]] & , pos]][[2]], {2}]
Out[7]= {7, 4, 5, 5, 4}
Fred Simons Eindhoven University of Technology
 Original Message  From: <mchangun@gmail.com> Subject: Add terms surrounded by zero together in matrix
> 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! >

