Search code examples
multidimensional-arraymicropython

How do I fill a 3d array with 0's without Numpy


I am using a 3d array to control a RGB Led matrix via a micro controller using MicroPython. I can't use Numpy to make the array. But it needs to be filled in order for the rest of the code to call on versus positions. It would be nice if it can be done by a function so that I can use the code on different sized Led panels.

Right now I write the whole thing out but that does not scale and it slows down the editor a lot. the other thing that I have tried is a function to do it. but I don't know how to add the value instead of the reference.

def setbase():
    base2 = []
    for y in range(WIDTH):
            base2.insert(y,[0,0,0])
    
    for x in range(HEIGHT):
        base.insert(x,base2)

Solution

  • Because you are just generating 0 values, you can use append which may be a bit faster. Is something like this what you're looking for?

    def setbase(m, n, channels = 3):
        panel = []
        for k in range(channels):
            panel.append([])
            for j in range(m):
                panel[k].append([0 for i in range(n)])
        return panel
    

    Example:

    setbase(5, 4)
    
    # Returns
    [
      [
        [0, 0, 0, 0], 
        [0, 0, 0, 0], 
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]
      ], [
        [0, 0, 0, 0], 
        [0, 0, 0, 0], 
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]
      ], [
        [0, 0, 0, 0], 
        [0, 0, 0, 0], 
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]
      ]
    ]
    

    If you're looking to take as input some panel object and populate it with 0 values we'd have to see the panel object first. That said, assuming its representation is similar to a NumPy array (which seems fairly likely) it'd probably be something like this:

    m, n, k = 5, 4, 3
    panel = np.ones((k, m, n))
    
    print(panel)
    
    def setbase(panel):
        for k, channel in enumerate(panel):
            for i, row in enumerate(channel):
                for j, col in enumerate(row):
                    panel[k,i,j] = 0
        return panel
    
    print(panel)
    

    You can also speed up these sorts of computations (e.g. nested for loops) by importing Numba and using one of their decorators. See the docs.