-1

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?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    Please, provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Suthiro Dec 04 '20 at 21:26

1 Answers1

0

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.

dhutama
  • 56
  • 4
  • My goal is to estimate the average value of the top regions and of the bottom regions. Obviously this could be done by hand but I have several of such plots with varying parameters for such square waves. – luca gravina Dec 05 '20 at 18:09