Home > front end >  Is there any available function in numpy that iterate a ndarray and modify each element with a custo
Is there any available function in numpy that iterate a ndarray and modify each element with a custo

Time:04-14

def evolve(self):
    newgrid =signal.convolve2d(self.grid, self.neighborhood, 'same')
    dimentionX = self.grid.shape[0]
    dimentionY = self.grid.shape[1]
    for i in range(0, dimentionX):
        for j in range(0, dimentionY):
            if newgrid[i,j] < 2:
                self.grid[i,j] = self.deadValue
            elif newgrid[i,j] == 3:
                self.grid[i,j] = self.aliveValue
            elif newgrid[i,j] > 3:
                self.grid[i,j] = self.deadValue
    return self.grid

I am doing something like this. This function is frequently called. It was fine when the grid is not large (64x64 for examplee). However, when the grid has with more than a thousand, the simulation runs very slow.

I was told that with appropriate use of numpy it should be much more faster. I was told that numpy provides such a function that does the same thing as what I have written, but much faster.

After some research at the documentations, I only found this: enter image description here

But this only support boolean return type, and only support simple callback for each element, while I need to do complex operation (that is multilined and involves 'if's) for each element

CodePudding user response:

Note that I do not discuss you approach as such. I strictly address your question.


What about resorting to boolean indexing ? As follows

# [...]
self.grid[(newgrid < 2) | (newgrid > 3)]  = self.deadValue
self.grid[newgrid == 3] = self.aliveValue
# [...]

?

CodePudding user response:

The function is np.where

def evolve(self):
    newgrid = signal.convolve2d(self.grid, self.neighborhood, 'same')
    self.grid = np.where(newgrid == 3, self.aliveValue, self.deadvalue)
    return self.grid
  • Related