here is my code:
def posrand():
loc = [1, 2]
location = random.choice(loc)
if location == 1:
pos1 = [-.05,-.05]
pos2 = [.05, .05]
else:
pos1 = [.05, .05]
pos2 = [-.05, -.05]
# displays window and stimulus
win = visual.Window(size=(1920, 1080), fullscr=True, screen=0, monitor='testMonitor', color=[-1,-1,-1])
distractorstim = visual.ImageStim(win=win, pos=pos1, size=[0.5,0.5])
distractorstim.autoDraw = True
targetstim = visual.ImageStim(win=win, pos=pos2, size=[0.5,0.5])
targetstim.autoDraw = True
for i in range(len(ac)):
posrand()
targetstim.image = target[i]
distractorstim.image = distractor[i]
win.flip()
core.wait(1)
What I am trying to do is have the posrand function run on every trial, so that the location is always shuffled between these two locations. However, it doesn't read to pos1 and pos2 values. If the put the window and stimulus information into the posrand function, it works, but the program will run into errors when I try to process a lot of images. How can I do this so that pos1 and pos2 values can be updated on the stimulus, but so that I don't have to constantly redraw the stimulus? Any help will be greatly appreciated. :)
2 Answers 2
The explanation of your problem is not very complete, but at the first glance: pos1 and pos2 are only available to posrand: they are local variables. The changes you do there are not reflected outside of it.
You may want to define these two variables on module level and then access them inside of posrand using the variable declaration global or nonlocal on python 3. That way the calls to posrand will mutate outer state (that I assume from your explanation that will impact the behaviour of the visual.ImageStim instances).
You can try this:
pos1, pos2 = [], []
def posrand():
global pos1
global pos2
loc = [1, 2]
location = random.choice(loc)
if location == 1:
pos1 = [-.05,-.05]
pos2 = [.05, .05]
else:
pos1 = [.05, .05]
pos2 = [-.05, -.05]
This is however, a very poor programming approach. Relying on mutable global variables darkens the logic of your programme. You most probably should re-instantiate these visual.ImageStim objects on each loop pass.
2 Comments
Your posrand is creating local variables. To modify the global variables you should do a splice assignment:
if location == 1:
pos1[:] = [-.05,-.05]
pos2[:] = [.05, .05]
else:
pos1[:] = [.05, .05]
pos2[:] = [-.05, -.05]