Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.


Math Forum » Discussions » Software » comp.soft-sys.math.mathematica

Topic: Add terms surrounded by zero together in matrix
Replies: 6   Last Post: Jul 31, 2005 1:37 AM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Simons, F.H.

Posts: 107
Registered: 12/7/04
Add terms surrounded by zero together in matrix
Posted: Jul 31, 2005 1:08 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

I consider two non-zero 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!
>





Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.