0

I am getting following error when I am plotting the FFT of signal. The code reads the signal samples from the .txt file. TypeError: Cannot cast array data from dtype('S17') to dtype('complex128') according to the rule 'safe'

         #%% Import libraries
           import numpy as np
           from scipy import signal
           from scipy import fft,log10
           from scipy import ifft
           import matplotlib.pyplot as plt
           import scipy.fftpack

           #%%  Import signal
           text_file = open("sample.txt", "r")
           a=text_file.readlines()
           plt.figure(1)
           plt.plot(a)
           fs=1000
           t=np.arange(0,(len(a)))/float(fs)
           plt.figure(201)
           plt.plot(t,a)
           plt.title('Signal')
           plt.show()
#%% Plot FFT
n=len(a) # Number of samples
k=np.arange(n)
T=n/float(fs) # Sample spacing
frq=k/T
frq = k/T # two sides frequency range
frq = frq[range(n/2)] # one side frequency range

Y = np.fft.fft(a)/n # fft computing and normalization
Y = Y[range(n/2)]

plt.figure(203)
plt.plot(frq,np.abs(Y),'r')  # plotting the spectrum
plt.show()
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
Sachin Anchan
  • 21
  • 1
  • 3

1 Answers1

0

a=text_file.readlines() will give you a list of strings. You need to convert the strings to numbers (probably float) before you can do plot(a) or fft(a)

a=text_file.readlines()
a = [float(x) for x in a]
plt.figure(1)
plt.plot(a)
Y = np.fft.fft(a)
Julien Spronck
  • 15,069
  • 4
  • 47
  • 55