1

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)
Macwa
  • 13
  • 4

2 Answers2

0

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.

Greenstick
  • 8,632
  • 1
  • 24
  • 29
0

thank you Greenstick the first code you posted helped me te figure out how to do a for loop in a for loop in a for loop and that was enough to fill the array and make it run.

def setbase():
    for y in range(HEIGHT+1): #add 1 extra line so the moon & sun can be draw offmatrix
            base.append([])
            for x in range(WIDTH):
                base[y].append([0 for k in range(3)])
Macwa
  • 13
  • 4