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

I am trying to create a list of xy positions that represent a raster scan pattern like below:

enter image description here

Simply put I am using nested loops and if else statements but it is getting messy. Is there a simple way generate a list of positions with a fixed step size?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

One possible solution, using a mix of Numpy and normal Python:

from pylab import *

# define some grids
xgrid = arange(20, 31) 
ygrid = arange(10, 16)

xscan = []
yscan = []

for i, yi in enumerate(ygrid):
    xscan.append(xgrid[::(-1)**i]) # reverse when i is odd
    yscan.append(ones_like(xgrid) * yi)   

# squeeze lists together to vectors
xscan = concatenate(xscan)
yscan = concatenate(yscan)

# quick plot
plot(xscan, yscan, '.-')
axis([19, 31, 9, 16])
show()

The way this works is to define 2 empty lists for x and y, to which you append one scan-line at a time. For the x-coordinates, you alternatively need a forward and a backward line (xgrid[::1] for forward and xgrid[::-1] for backwards, the alternating +1 and -1 are obtained by (-1)**i), while for the y-coordinate, you have to repeat a single y-value for each x-coordinate. In the end, you have to concatenate the list of vectors into a single vector.

The same can be achieved without any for-loops using a list-comprehension and repeat, like so:

xscan = concatenate([xgrid[::(-1)**i] for i in range(len(ygrid))])
yscan = repeat(ygrid, len(xgrid))

Resulting scan pattern: raster scan

share|improve this answer
 
Interesting, could you explain how the loop works? It seems relatively incomprehensible to me at my current level of knowledge. Thanks! –  user2221667 13 hours ago
 
I added some more explanation, I hope it is clear now. If not, try to work through some basic python and numpy tutorials. –  Bas Swinckels 12 hours ago
add comment

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.