0

I am a novice in Python and I am trying to create a little animation of the linear convolution.

from matplotlib import pyplot as plt
from matplotlib import animation
import math


def creer_y1():

   y1=[]
   return y1

def update_y1(i,y1):
   
   y1=[0,1,1,1,0]
   return y1,

def creer_y2():

   y2=[]
   return y2

def update_y2(i,y2):
   
   y2_stock = [0,0,0,0,0, 1,0,0,0,0, 1,1,0,0,0, 1,1,1,0,0 ,0,1,1,1,0 ,0,0,1,1,1 ,0,0,0,1,1 ,0,0,0,0,1, 0,0,0,0,0]
   y2 = y2_stock[0+5*i:5+5*i]
   
   print(y2)
   return y2,

def creer_convo():

   convo=[]
   return convo

def update_convo(i,y1,y2,convo):
   

   convo[i]=y1[0]*y2[0]+y1[1]*y2[1]+y1[2]*y2[2]+y1[3]*y2[3]+y1[4]*y2[4]
   print(convo)
   return convo,

def create_animation():
   
   fig = plt.gcf()
   ax = plt.axes(xlim=(0,10), ylim=(0,2))
   ax.set_aspect('equal')
   
   y1=creer_y1()
   y2 = creer_y2()
   convo=creer_convo()

   anim1 = animation.FuncAnimation(fig,update_y1,fargs=(y1,),frames=9,interval=1000)
   anim2 = animation.FuncAnimation(fig,update_y2,fargs=(y2,),frames=9,interval=1000)
   anim_convo = animation.FuncAnimation(fig,update_convo,fargs=(y1,y2,convo,),frames=9,interval=1000)
  
   plt.title('Linear Convolution Animation')
   plt.show()

if __name__=='__main__':
    create_animation()

The error message is the following:

convo[i]=y1[0]*y2[0]+y1[1]*y2[1]+y1[2]*y2[2]+y1[3]*y2[3]+y1[4]*y2[4]
IndexError: list index out of range

And I suppose it occurs because when I try to call update_convo through animation_convo it passes non updated versions of y1 and y2 to update_convo.

I have tried to investigate how to deal with it and one of the solution appears to be using the module ctypes in order to use sort of pointers in Python. However I assume that it is a bit overkilled in my case and I wondered if their was any way to pass the reference to the PyObject of y1 and y2 to my fonction update_convo.

I hope my question is clear enough and I would be so grateful to anyone helping me or giving me pieces of information.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • You don't need ctypes or PyObject to solve a simple `IndexError`. In this case, I think the cause is simply that `y2` is initially an empty list, so even `y2[0]` is already out of range. – Thomas Jun 25 '21 at 09:41
  • Thanks a lot, I'll try to correct it without PyObject and ctypes then. – AlderiateFanClub Jun 25 '21 at 09:45
  • "And I suppose it occurs because when I try to call update_convo through animation_convo it passes non updated versions of y1 and y2 to update_convo." no? Why do you suppose that? – juanpa.arrivillaga Jun 25 '21 at 09:58
  • Do you *mean* to `return y1,` with that comma? – juanpa.arrivillaga Jun 25 '21 at 10:00
  • when I added print(y1) and print(y2) in update_convo it returned [] for both of them that is why I took this guess. But I surely don't understand how the whole thing works. – AlderiateFanClub Jun 25 '21 at 10:04

0 Answers0