0

Whilst programming Cellular-Automaton (obviously not finished) I encountered issues with bounds. The goal for the result of this section is to have a value in the position (i,j) on a matrix depicting the average of a random value (and its direct neighbours) between 0 and 1.

How can I manage this without violating the boundary conditions/rules?

import numpy as np

def arr(size):
    arraySize = size
    Z = np.array([[np.random.uniform(0, 1) for x in range(arraySize)] for y in range(arraySize)])
    return Z

def each_average(i,j,array):
    x= (array[i])+(array[i+1])+(array[i-1])
    y= x[j-1]+x[j]+x[j+1]
    f= y/9
    return f


def average(array):
    i,j=0,0
    average=[]
    while j in range(len(array)):
        while i in range(len(array)):
            i=i+1
            j=j+1
            x = each_average(i,j,array)
            average.append(x)
    return average

Z=arr(4)
print average(Z)
  • Why are you using while loops instead of fors? That looks strange to me. If you're trying to pair all possible values of `i` with all possible values of `j`, that's not what's happening here. If you put `print i, j` just before your `each_average` call, you'll see that i and j are always equal. – Kevin Apr 11 '14 at 13:15

1 Answers1

0
def each_average(i, j, matrix, size):
    size -= 1
    values = [matrix[i][j]]
    if i > 0:
        values.append(matrix[i-1][j])
    if i < size:
        values.append(matrix[i+1][j])
    if j > 0:
        values.append(matrix[i][j-1])
    if j < size:
        values.append(matrix[i][j+1])

    return sum(values)/5

Where size is the size of the matrix.

If you want to convert each of the values in the matrix to the average of it and its neighbours:

def average(matrix, size):
    average_matrix = []
    for i in range(size):
        average_matrix.append([])
        for j in range(size):
            average_matrix[i].append(each_average(i, j, matrix, size))
    return average_matrix

However, this is inefficient, as there's no need to pass in the whole matrix again.

def average(matrix, size):
    size -= 1
    average_matrix = []
    for i in range(size):
        average_matrix.append([])
        for j in range(size):
            values = [matrix[i][j]]
            if i > 0:
                values.append(matrix[i-1][j])
            if i < size:
                values.append(matrix[i+1][j])
            if j > 0:
                values.append(matrix[i][j-1])
            if j < size:
                values.append(matrix[i][j+1])
            average_matrix.append(sum(values)/5)
    return average_matrix
Scorpion_God
  • 1,499
  • 10
  • 15