Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i have this :

npoints=10

vectorpoint=random.uniform(-1,1,[1,2])
experiment=random.uniform(-1,1,[npoints,2])

and now i want to create an array with dimensions [1,npoints]. I can't think how to do this. For example table=[1,npoints]

Also, i want to evaluate this:

for i in range(1,npoints):
    if experiment[i,0]**2+experiment[i,1]**2 >1:
        table[i]=0
    else:
        table[i]=1

I am trying to evaluate the experiment[:,0]**2+experiment[:,1]**2 and if it is >1 then an element in table becomes 0 else becomes 1.

The table must give me sth like [1,1,1,1,0,1,0,1,1,0]. I can't try it because i can't create the array "table". Also,if there is a better way (with list comprehensions) to produce this..

Thanks!

share|improve this question

1 Answer 1

up vote 2 down vote accepted

Try:

table = (experiment[:,0]**2 + experiment[:,1]**2 <= 1).astype(int)

You can leave off the astype(int) call if you're happy with an array of booleans rather than an array of integers. As Joe Kington points out, this can be simplified to:

table = 1 - (experiment**2).sum(axis=1).astype(int)

If you really need to create the table array up front, you could do:

table = zeros(npoints, dtype=int)

(assuming that you've already import zeros from numpy). Then your for loop should work as written.

Aside: I suspect that you want range(npoints) rather than range(1, npoints) in your for statement.

Edit: just noticed that I had the 1s and 0s backwards. Now fixed.

share|improve this answer
1  
It's a bit cleaner to just do table = numpy.sum(experiment**2, axis=1).astype(int) or equivalently table = (experiment**2).sum(axis=1).astype(int) –  Joe Kington Oct 28 '11 at 18:25
    
@Joe Kington. True! –  Mark Dickinson Oct 28 '11 at 18:33
    
@Joe Kington: Hmm. That gives the reverse of what's wanted; I added an extra 1 - to fix it. –  Mark Dickinson Oct 28 '11 at 18:38
    
Well, I misread things... I didn't notice the <=1, I was just referring to squaring and adding the two columns seperately. My equivalent would be (experiment**2).sum(axis=1) <= 1 (with wrapping the whole thing in astype(int), if ints are what the OP wants. That'll teach me to comment without reading everythign! –  Joe Kington Oct 28 '11 at 20:29
    
@Mark Dickinson:Thanks!It works fine!I wanted to ask how the <=1 evaluates the expression.I mean ,ok it means what i want(it implements the if statement) but where can i use such "tricks"?From where can i learn?Thanks again! –  George Oct 29 '11 at 8:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.