0

I have a problem with initializing an array in python. I have been trying to search for a solution, however I have not found anything. (It could be that I searched for wrong keywords). Anyways, this is what I am trying to achieve: I am writing a python script for a machine vision application. The application consists of several "tools" that are run iteratively in its ordered sequence. One of these tools I am writing as a python script. In this script I need to create an array type variable, that for each iteration will remove the first value and append a new value at the end. As it needs to remember the array between iterations, does it have to be global? The problem is that I need to define the variable as an array at the beginning of the script. For this, I use: xPosition_array = [] Later in the script, I append a value. However, next iteration xPosition_array = [] will overwrite the array with an empty one. How can I make the code such that the array is defined/initialized only once (first iteration)?

Thanks in advance.

The code:

global xPosition_array
xPosition_array = []
filter_win_len = 40

def moving_average(a, n) :
    ret = np.cumsum(a, dtype=float)
    ret[n:] = ret[n:] - ret[:-n]
    return ret[n - 1:] / n

xPosition = GetValue('LocatexPos.Line[1]_q_x')

if len(xPosition_array) < filter_win_len:
 xPosition_array.append(xPosition)
elif len(xPosition_array) == filter_win_len:
 xPosition_array.pop(0)
 xPosition_array.append(xPosition)

xPosition_filtered = moving_average(xPosition_array, filter_win_len)
John
  • 3
  • 1

2 Answers2

0

If you write the entire tool in a function, you can call the function and pass the array as an argument.

xPosition_array = []

def my_tool(xPosition_array):
    # do stuff

Each time you want to use the tool, just call the function.

I'm not exactly sure what you are trying to achieve here, so hope this is helpful.

Vibius
  • 171
  • 1
  • 7
0

You could try this for your initialization of the array:

global xPosition_array

if 'xPosition_array' in globals():
   pass
else:
    xPosition_array=[]

Then when you conduct further iterations you get the following:

global xPosition_array

#First Iteration: 

if 'xPosition_array' in globals():
   pass
else:
    xPosition_array=[]

print("First Iteration: ", xPosition_array)

#Set Variable after First Iteration:
xPosition_array=[0,1,2]

#Second Iteration:

if 'xPosition_array' in globals():
   pass
else:
    xPosition_array=[]

print("Second Iteration: ", xPosition_array)

Output:

First Iteration:  []
Second Iteration:  [0, 1, 2]

Then you should only set it as an empty array whenever it hasn't been defined yet. Assuming xPosition_array remains available to your main function calling your tool iteratively. See this answer: How do I check if a variable exists? for further checks for variables.

Community
  • 1
  • 1
Taylor Paul
  • 364
  • 2
  • 9