0

i'm trying to keep a value for freq. Every time i call the function cut, it changes it. On stack overflow i found that putting [:] should work, however in my code it doesn't. I'm using the cut function to assign value 0 to some fft values and then doing the ifft to get back a cleaner signal.

here is the code:

import numpy as np 
import matplotlib.pyplot as plt
#from scipy import signal



time=np.linspace(0,10, 10000)
sig=np.sin(np.pi*time*20)

plt.plot(time, sig)
plt.show()

def time_zero(t): #outputs a time array that begins from 0. 
    N=len(t) #number of total time points. 
    T=t[len(t)-1]-t[0]#total time in seconds
    dt=T/N  #each timespet
    fs=N/T
    t=np.arange(0,T,dt) #time array that begins from 0 
    return t,N,T,dt,fs


def transform (x,y):
    t,N,T,dt,fs=time_zero(x)
    fourier=np.fft.rfft(y, norm="ortho")
    freq=np.fft.rfftfreq(N,dt)
    return freq, fourier.real
#    s=np.fft.ifft(fourier)

def intransform (freq,fourier):
    t,N,T,dt,fs=time_zero(freq)
    signal=np.fft.irfft(fourier,norm="ortho")
    return signal


def cutter(freq,fft,cut):
    t,N,T,dt,fs=time_zero(freq)
    new_lst = fft[:][:] #makes a copy not just assigned the same value to 

the name https://stackoverflow.com/questions/24171120/variable-changes-without-being-touched

        for i in range (cut*int(fs),len(new_lst)):
            new_lst[i]=0
        return new_lst

freq, fft=transform(time,sig)

#
plt.plot(freq,fft)
plt.xlim(0,30)
plt.show()


cut=cutter(freq,fft, 3)

print (cut==fft)



plt.plot(freq,fft)
plt.xlim(0,30)
plt.show()


ifft=intransform(freq,fft)

#
plt.plot(time_zero(time)[0],ifft)

plt.show()
Leo
  • 1,176
  • 1
  • 13
  • 33
  • 1
    I haven't read your code, but you say "[:] should work", but that only applies to *lists* (and other built-in sequence type). For `numpy.ndarray` objects, `[:]` returns an array with the same underlying buffer as the object that the slice comes from, i.e., it's a view, not a copy. – juanpa.arrivillaga May 29 '18 at 17:03
  • Also, the answer you copied from is wrong even for lists - `some_list[:][:]` just performs two shallow copies, not a deep copy. – user2357112 May 29 '18 at 17:04
  • 2
    Anyway, `[:]` would only perform a shallow copy. If you are working with `numpy.ndarray` objects, then just use their `.copy` method. – juanpa.arrivillaga May 29 '18 at 17:04
  • The copy method woked, thanks – Leo May 29 '18 at 17:05

1 Answers1

-1

Create a new list like below: new_lst = [f for f in freq]