luca gravina
luca gravina

Reputation: 1

How to fit data with square wave in Python?

I have the following data:

Experimental data and ideal fitting function

I have been trying to fit it with a sequence of square pulses which I define as:

def f(x, x0, a, b, c):
    sq = a * np.ones_like(x)
    sq[(x>x0) * (x<x0+b)] = c
    sq[(x>x0+2*b) * (x<x0+3*b)] = c
    sq[(x>x0+4*b) * (x<x0+5*b)] = c
    return sq

The problem is that fitting with curve_fit I get a straight line or a square pulse whose max and min lie above the max of the data. How is this possible? How can I implement it properly?

Upvotes: -1

Views: 936

Answers (1)

dhutama
dhutama

Reputation: 56

What is your end goal, and is your approach the best way? I would think that you can Fourier transform your data to find the square wave Fourier coefficients. Taking the first n components and plotting the result will give you a periodic curve that is square-ish and "fits" the data.

Upvotes: 0

Related Questions