[SciPy-user] Would like to simplify my 3 where statements

Michael Sorich michael.sorich at gmail.com
Thu Jul 20 23:56:12 EDT 2006


If I run the script below I get [0,2]. Is this what you want? In any
case the code you wrote looks fairly simple now. An alternative
function to where is nonzero, however this will not make and
difference.

from numpy import *
i=3
j=4
A = array([[0, 1, 0, 1, 0],
      [1, 0, 1, 0, 1],
      [1, 0, 0, 0, 0],
      [0, 0, 1, 0, 1],
      [1, 1, 0, 1, 0]])
ans=where(A[:,j]==1)[0] #ans=[1,3]
if A[i,j] == 1:
   ans -= 1
print ans
>> [0 2]

On 7/21/06, David Grant <davidgrant at gmail.com> wrote:
> On 7/20/06, Michael Sorich <michael.sorich at gmail.com> wrote:
> > Can you give an specific example of how this would work? The codes
> > really is ugly and it is not clear to me what exactly it does.
>
> ok here's a quick example:
>
> import numpy
> n=5
> i=3
> j=4
> A=numpy.random.randint(0,2,(n,n)) #make random graph
> A=A-diag(diag(A)) #remove diagonal
> A=triu(A)+transpose(triu(A)) #make symmetric
>
> Now say A is the adjacency matrix for a graph and I want to know which
> nodes are neighbours of A, but I want to exclude node i from
> consideration. So if A is:
>
> array([[0, 1, 0, 1, 0],
>        [1, 0, 1, 0, 1],
>        [1, 0, 0, 0, 0],
>        [0, 0, 1, 0, 1],
>        [1, 1, 0, 1, 0]])
>
> the neighbours are array([1]) for i=3, j=4.
>
> One way to do it is to do:
>
> ans=where(A[:,j]==1)[0]
> if A[i,j] == 1:
>     ans -= 1
>
> which is probably faster than my method. I don't really care so much
> about speed though. I'm just trying to figure out different ways of
> doing this using numpy.
>
> Dave
> _______________________________________________
> SciPy-user mailing list
> SciPy-user at scipy.org
> http://projects.scipy.org/mailman/listinfo/scipy-user
>



More information about the SciPy-User mailing list