Re: Please Help
- To: mathgroup at smc.vnet.net
- Subject: [mg4129] Re: Please Help
- From: lou (Lou D'Andria)
- Date: Wed, 5 Jun 1996 01:40:18 -0400
- Organization: Wolfram Research, Inc.
- Sender: owner-wri-mathgroup at wolfram.com
In article <4ojdv2$5i8 at dragonfly.wolfram.com>, takuo at psy.uwa.edu.au (Takuo Henmi) wrote: >My question is how to find the max. value of its neighbors in a matrix, i.e. > >if you have a matrix > > 1 2 3 > 2 3 4 > 2 1 1 > >(it'll always be a square matrix) > >the max of the neighbors of cell [1,1] would be 3 (cell [2,2]), right? >so new cell [1,1] will be 3. Like that, you'll have a new matrix, in this case, > > > 3 4 4 > 3 4 4 > 3 4 4 > >(including the cell itself, e.g. cell [2,3]) and the boundaries are all 0s. I'm not sure what you mean by "the boundaries are all 0s." I interpreted this to mean that the numbers in the input matrix will all be positive, and so if I wanted to add a boundary of zeros temporarily for comparison, that would be ok. To add a boundary of zeros around a rectangular matrix m, I will use Join[{#},Join[{0},#,{0}]& /@ m,{#}]& @ Table[0,{2 + Length[First[m]]}] Once you've got this border of zeros around the original matrix, you can use Partition to get the neighborhoods, and Max to find the maximum in each neighborhood. ============================ In[1]:= NeighborhoodMaxes::usage = "NeighborhoodMaxes[mat] gives the matrix of neighborhood maximums of a rectangular matrix mat."; In[2]:= NeighborhoodMaxes[ mat_?(MatrixQ[#,Positive]&) ] := Apply[Max, Partition[#,{3,3},{1,1}], {2}]& @ Join[{#},Join[{0},#,{0}]& /@ mat,{#}]& @ Table[{0},{2 + Length[First[mat]]}] In[3]:= NeighborhoodMaxes[{{1,2,3},{2,3,4},{2,1,1}}] Out[3]= {{3, 4, 4}, {3, 4, 4}, {3, 4, 4}} In[4]:= TableForm[ m = Table[ Random[Integer,{1,9}], {3},{10}] ] Out[4]//TableForm= 1 4 1 5 4 4 4 7 2 6 2 1 7 8 9 6 2 6 6 8 3 6 6 9 5 1 1 7 4 9 In[5]:= TableForm[ NeighborhoodMaxes[m] ] Out[5]//TableForm= 4 7 8 9 9 9 7 7 8 8 6 7 9 9 9 9 7 7 9 9 6 7 9 9 9 9 7 7 9 9 ============================ I can't take credit for discovering this Partition method of extracting neighborhoods, but I no longer remember who first showed it to me. If negative numbers are allowed in your matrices (and I misunderstood your "boundary" statement - sorry), then replace all the zeros in the definition of NeighborhoodMaxes with -Infinity. The zero is really just a placeholder, and can be replaced by anything that is guaranteed to be at least as small as every matrix element. To be completely safe, it can even be replaced by Min[mat]. Lou ==== [MESSAGE SEPARATOR] ====