# Fitting data to a square wave

**URL:** <https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062>\
**Category:** Questions\
**Tags:** image-processing, physics, signal-processing, curated-data, graphics-and-visualization, modeling\
**Created:** [January 29, 2025, 7:11pm UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062 "2025-01-29T19:11:09Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![hall9](https://avatars.discourse-cdn.com/v4/letter/h/f07891/32.png) [@hall9](https://community.wolfram.com/u/hall9)\
**Post date:** [January 29, 2025, 7:11pm UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/1 "2025-01-29T19:11:09Z")

</div>

I have a question about the attached MM notebook (just a few lines). I’m trying to fit a lineout through the digital image of a line pair gauge to a square wave. FindFit appears to fit the mean value (b) and at least takes a stab at fitting the amplitude (a); however, it seems to make no attempt to fit the offset on the x axis (x0). Why not? What am I missing?

Also, I would like to get more detail on the fit parameters, in particular, the uncertainties, but I haven’t been able to figure out how to get MM to dump that information. How can I do that?

Thanks in advance for any help on this.

[Open in Wolfram Cloud ↗](https://www.wolframcloud.com/obj/4ffdae82-d8c3-4e82-b69c-9d0b6f58a3af)

[LPG 07-1.txt](https://community.wolfram.com/uploads/short-url/2hdq5oduLid8KpUVB6XsQFeyC2r.txt) (529 Bytes)

---

<div class="post-metadata">

**Author:** ![antononcube](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/antononcube/32/7348_2.png) [@antononcube](https://community.wolfram.com/u/antononcube)\
**Post date:** [January 29, 2025, 8:14pm UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/2 "2025-01-29T20:14:15Z")

</div>

`NonlinearModelFit` works better for this:

 ![NonlinearModelFit-for-SqWave.png](https://global.discourse-cdn.com/wolfram/original/3X/3/2/32503255896c66db46619391455597f98c3dbea4.png)

---

<div class="post-metadata">

**Author:** ![dlkeith](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/dlkeith/32/31494_2.png) [@dlkeith](https://community.wolfram.com/u/dlkeith)\
**Post date:** [January 29, 2025, 8:49pm UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/3 "2025-01-29T20:49:10Z")

</div>

Hi James,

In the attached notebook, I first fit the data to a sine function, and then use the determined parameters as estimates for fitting to the square wave. I used NonlinearModelFit, which provides statistics on the fit.

[MMSW fit 2-DK2.nb](https://community.wolfram.com/uploads/short-url/ltM8LYhm0ImT5B6wS48gakCsXJA.nb) (182 KB)

---

<div class="post-metadata">

**Author:** ![jmhall52](https://avatars.discourse-cdn.com/v4/letter/j/e47c2d/32.png) [@jmhall52](https://community.wolfram.com/u/jmhall52)\
**Post date:** [January 29, 2025, 9:39pm UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/4 "2025-01-29T21:39:46Z")

</div>

Thanks for your input, Anton. I appreciate your help. Did this actually use x0 as a fit parameter? It look like it just set the value to 1.000… with 0 uncertainty.

---

<div class="post-metadata">

**Author:** ![jmhall52](https://avatars.discourse-cdn.com/v4/letter/j/e47c2d/32.png) [@jmhall52](https://community.wolfram.com/u/jmhall52)\
**Post date:** [January 29, 2025, 9:56pm UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/5 "2025-01-29T21:56:00Z")

</div>

Thanks, David. Using a Sin fit looks like a good way to define x0 and estimate starting values for a & b. There are several other techniques you included that I can make use of. I’m puzzled that the amplitude (a) turns out to be negative (not sure what that means), and I’m a bit surprised/disappointed that the fit value doesn’t match the approximate max & min values of the data better than it does, because I would like to use this technique to estimate the gauge modulation ((max-min)/(max+min)).

Again, thanks much for your help - I really appreciate it.

---

<div class="post-metadata">

**Author:** ![dlkeith](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/dlkeith/32/31494_2.png) [@dlkeith](https://community.wolfram.com/u/dlkeith)\
**Post date:** [January 30, 2025, 1:19am UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/6 "2025-01-30T01:19:37Z")

</div>

Hi James,  
The parameter a being negative is only a phase inversion, which would be compensated in the fit by a different value of x0. It can be forced positive by including a condition in the model like this:

```
sinFit = 
 NonlinearModelFit[LPGdata, {sineWave[x, a, x0, b], a > 0}, {a, x0, b},
   x]

```

I am also disappointed that the peaks are modeled poorly in the square wave fit. It is likely due to the midlevel values in the data. Stripping these out before the fit could improve the result. But data manipulation carries its own risks.

---

<div class="post-metadata">

**Author:** ![jmhall52](https://avatars.discourse-cdn.com/v4/letter/j/e47c2d/32.png) [@jmhall52](https://community.wolfram.com/u/jmhall52)\
**Post date:** [January 30, 2025, 3:35am UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/7 "2025-01-30T03:35:57Z")

</div>

Quite so, David, and a subjective data analysis was precisely what I was hoping to avoid by doing this fit. Thanks again. - Jim

---

<div class="post-metadata">

**Author:** ![jari](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/jari/32/2115_2.png) [@jari](https://community.wolfram.com/u/jari)\
**Post date:** [January 30, 2025, 4:49am UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/8 "2025-01-30T04:49:58Z")

</div>

Frankly I would find the phase separately by brute force, using reasonable candidate values (`timesinbetween` below). `SqWave` is just a pathologically nasty function to fit automatically. I would also, probably, rewrite `SqWave` in some other form (like `SquareWave`?), but here the method below doesn’t really care about that:

[Open in Wolfram Cloud ↗](https://www.wolframcloud.com/obj/70a0dcf8-f03a-4330-a256-5d0545635231)

---

<div class="post-metadata">

**Author:** ![drjbaldwin](https://avatars.discourse-cdn.com/v4/letter/d/ebca7d/32.png) [@drjbaldwin](https://community.wolfram.com/u/drjbaldwin)\
**Post date:** [January 30, 2025, 5:08am UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/9 "2025-01-30T05:08:29Z")

</div>

I’m curious as to how you created the simulated data. I ask because if you sampled a square wave from x=-6.3 to x=4.8 with a constant error variance over a cycles of a square wave, it would seem near impossible to get any of those 6 points in the middle of the figure (i.e., those points between y=0.01 and y=0.03).

In other words, those 6 points could be considered outliers and maybe given very little weight.

---

<div class="post-metadata">

**Author:** ![drjbaldwin](https://avatars.discourse-cdn.com/v4/letter/d/ebca7d/32.png) [@drjbaldwin](https://community.wolfram.com/u/drjbaldwin)\
**Post date:** [January 30, 2025, 5:55am UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/10 "2025-01-30T05:55:22Z")

</div>

Given my previous comments, I wonder if your data was generated by a trapezoidal wave rather than a square wave.

```
data={{-6.25, 0.00219649}, {-5.75, 0.0291773}, {-5.25, 0.0428364}, {-4.75, 0.0418075}, 
  {-4.25, 0.0390189}, {-3.75, 0.0142977}, {-3.25, 0.000728449}, {-2.75, 0.000577218}, 
  {-2.25, 0.00314383}, {-1.75, 0.0275447}, {-1.25, 0.0428128}, {-0.75, 0.0433703}, 
  {-0.25, 0.0433703}, {0.25, 0.0403935}, {0.75, 0.0160277}, {1.25, 0.000686316}, 
  {1.75, 0.00036222}, {2.25, 0.00288114}, {2.75, 0.0256044}, {3.25, 0.0416728}, 
  {3.75, 0.0429419}, {4.25, 0.0396677}, {4.75, 0.0162309}};

nlm = NonlinearModelFit[data,
   (a/\[Pi])*(ArcSin[Sin[(\[Pi]/m) x + l]] + ArcCos[Cos[(\[Pi]/m) x + l]]) - a/2 + c,
   {{a, 0.04}, {m, 2}, {l, 3}, {c, 0.02}}, x];
Show[ListPlot[data], Plot[nlm[x], {x, Min[data[[All, 1]]], Max[data[[All, 1]]]}]]

```

 ![trapezoidalwavefit.png](https://global.discourse-cdn.com/wolfram/original/2X/b/b0fc822c2bb5394484cca25a370e503a50b4c0e1.png)

The equation was lifted from Amrtanshu Raj 's answer at [https://uk.mathworks.com/matlabcentral/answers/684163-generating-periodic-trapezoidal-waves-with-ramps](https://uk.mathworks.com/matlabcentral/answers/684163-generating-periodic-trapezoidal-waves-with-ramps). (Yes, a MATLAB site.)  
[1]: [https://community.wolfram.com//c/portal/getImageAttachment?filename=trapezoidalwavefit.png&userId=3318986](https://community.wolfram.com//c/portal/getImageAttachment?filename=trapezoidalwavefit.png&userId=3318986)

---

<div class="post-metadata">

**Author:** ![claudemante1](https://avatars.discourse-cdn.com/v4/letter/c/c6cbf5/32.png) [@claudemante1](https://community.wolfram.com/u/claudemante1)\
**Post date:** [January 30, 2025, 10:30am UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/11 "2025-01-30T10:30:59Z")

</div>

It could be natural to use Haar wavelets…  
But the fit is not very good.

[Haar.nb](https://community.wolfram.com/uploads/short-url/m6cjuduDnKZEs63SNj00GJIqx2N.nb) (154 KB)

---

<div class="post-metadata">

**Author:** ![jmhall52](https://avatars.discourse-cdn.com/v4/letter/j/e47c2d/32.png) [@jmhall52](https://community.wolfram.com/u/jmhall52)\
**Post date:** [January 30, 2025, 6:21pm UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/12 "2025-01-30T18:21:08Z")

</div>

The data file is a scan through the simulated digital image of a rectangular line pair gauge. The detector has limited resolution, which is why the maxima show rolloff effects.

---

<div class="post-metadata">

**Author:** ![jmhall52](https://avatars.discourse-cdn.com/v4/letter/j/e47c2d/32.png) [@jmhall52](https://community.wolfram.com/u/jmhall52)\
**Post date:** [January 30, 2025, 6:31pm UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/13 "2025-01-30T18:31:35Z")

</div>

This looks very promising! Thanks much! I’ll give it a try.

---

<div class="post-metadata">

**Author:** ![dlkeith](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/dlkeith/32/31494_2.png) [@dlkeith](https://community.wolfram.com/u/dlkeith)\
**Post date:** [January 30, 2025, 8:02pm UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/14 "2025-01-30T20:02:37Z")

</div>

Hi Jamesa,  
The attached notebook takes a perhaps too naïve approach. It does select data to be processed. It estimates the peaks using data with y values greater then 80% of the max, and the valleys using values less than 20% of the max.

 ![rangefit.png](https://global.discourse-cdn.com/wolfram/original/2X/5/579bd28db4d761f3d4168e2628932f78241b613f.png)

[MinMax by Data Ranges 1\_0.nb](https://community.wolfram.com/uploads/short-url/dDzAG5A6FYV8NO9jf4tNF2K56AR.nb) (41.2 KB)

---

<div class="post-metadata">

**Author:** ![mariuszi28cg](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/mariuszi28cg/32/308_2.png) [@mariuszi28cg](https://community.wolfram.com/u/mariuszi28cg)\
**Post date:** [January 30, 2025, 11:16pm UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/15 "2025-01-30T23:16:06Z")

</div>

Maybe:

[Open in Wolfram Cloud ↗](https://www.wolframcloud.com/obj/2d5ae179-4925-4ddb-80fa-c88145583bb0)

---

<div class="post-metadata">

**Author:** ![jbaldwinpsw](https://avatars.discourse-cdn.com/v4/letter/j/ee7513/32.png) [@jbaldwinpsw](https://community.wolfram.com/u/jbaldwinpsw)\
**Post date:** [January 31, 2025, 1:48am UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/16 "2025-01-31T01:48:58Z")

</div>

I believe you that the “maxima show rolloff effects.” But what does that mean? I don’t speak that language. Might there be a need to include that “effect” in the modeling?

---

<div class="post-metadata">

**Author:** ![jbaldwinpsw](https://avatars.discourse-cdn.com/v4/letter/j/ee7513/32.png) [@jbaldwinpsw](https://community.wolfram.com/u/jbaldwinpsw)\
**Post date:** [January 31, 2025, 4:54am UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/17 "2025-01-31T04:54:33Z")

</div>

Knowledge of the data generation process is essential to get a good fit AND the “confidence” to trust predictions. You’ve mentioned limited resolution resulting in a “rolloff effect”. That should be included in any modeling.

Maybe those issues result in departures from a square wave. So here is another parameterization of a trapezoidal wave. One feature is that one of the parameters (`delta`) is a measure of departure from a square wave. A delta value of zero results in a square wave. Below is a crude figure showing the parameterization for a single wave:

 ![wave.png](https://global.discourse-cdn.com/wolfram/original/3X/3/e/3e58f8e2302e5d6893bae5198f64fa857fc108e1.png)

```
(* Trapezoidal wave function *)
f[x_?NumericQ, wavelength_?NumericQ, amplitude_?NumericQ, 
  phase_?NumericQ, base_?NumericQ, delta_?NumericQ] := Module[{s, y},
  s = Mod[x - phase, wavelength];
  If[s <= delta, y = base + amplitude s/delta,
   If[delta < s <= wavelength/2, y = base + amplitude,
    If[wavelength/2 < s <= wavelength/2 + delta, 
     y = base + amplitude (1 - (s - wavelength/2)/delta),
     y = base]]];
  y
  ]

data = {{-6.25, 0.00219649}, {-5.75, 0.0291773}, {-5.25, 0.0428364}, {-4.75, 0.0418075},
   {-4.25, 0.0390189}, {-3.75, 0.0142977}, {-3.25, 0.000728449}, {-2.75, 0.000577218},
   {-2.25, 0.00314383}, {-1.75, 0.0275447}, {-1.25, 0.0428128}, {-0.75, 0.0433703},
   {-0.25, 0.0433703}, {0.25, 0.0403935}, {0.75, 0.0160277}, {1.25, 0.000686316},
   {1.75, 0.00036222}, {2.25, 0.00288114}, {2.75, 0.0256044}, {3.25, 0.0416728},
   {3.75, 0.0429419}, {4.25, 0.0396677}, {4.75, 0.0162309}};

nlm = NonlinearModelFit[data, f[x, wavelength, amplitude, phase, base, delta],
   {{wavelength, 4}, {amplitude, 0.04}, {phase, 2}, {base, 0}, {delta, 0.5}}, x];

Show[ListPlot[data], Plot[nlm[x], {x, Min[data[[All, 1]]], Max[data[[All, 1]]]}]]

```

 ![trapwavefit.png](https://global.discourse-cdn.com/wolfram/original/2X/5/559486a776b662d24b3400fe560ad4b2348535a2.png)

```
nlm["ParameterTable"]

```

 ![parametertable.png](https://global.discourse-cdn.com/wolfram/original/2X/4/44002497b6fffad0b6dae6a9c53b7636959162ce.png)

One can see that `delta` (the parameter characterizing the departure from a square wave) is highly significant (meaning it is significantly different from zero). While the underlying physical process might be a square wave, the measurement process does not result in a square wave and maybe a trapezoidal wave is a better approximation of the results from measurements.

You can compare all of models in the provided answers using `nlm["AICc"]`. This provides a relative ranking of the models from all of the answers here with the better models having smaller AICc values.

---

<div class="post-metadata">

**Author:** ![jmhall52](https://avatars.discourse-cdn.com/v4/letter/j/e47c2d/32.png) [@jmhall52](https://community.wolfram.com/u/jmhall52)\
**Post date:** [January 31, 2025, 10:45pm UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/18 "2025-01-31T22:45:11Z")

</div>

Thanks for such a detailed response, Jim. I’ll give this a try.

---

<div class="post-metadata">

**Author:** ![anon21378091](https://avatars.discourse-cdn.com/v4/letter/a/bcef8e/32.png) [@anon21378091](https://community.wolfram.com/u/anon21378091)\
**Post date:** [February 5, 2025, 9:18pm UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/19 "2025-02-05T21:18:22Z")

</div>

Hi Mariusz,

I’ve played around with your suggested fit function and it seems to work pretty well in my application; however, I can’t quite figure out how to use the fit parameters to derive the max and min of the curve. I need to know how to do that in order to use the standard errors in the parameters to determine the uncertainty the gauge modulation (mod = ((max-min)/(max+min)). Can you give me any insight as to how to do that? If so, please let me know.

Thanks much,

Jim

---

<div class="post-metadata">

**Author:** ![dlkeith](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/dlkeith/32/31494_2.png) [@dlkeith](https://community.wolfram.com/u/dlkeith)\
**Post date:** [February 6, 2025, 1:06am UTC](https://community.wolfram.com/t/fitting-data-to-a-square-wave/25062/20 "2025-02-06T01:06:19Z")

</div>

Hi Jim,  
I’ll take the liberty of answering for Marius.

His very useful model is

```
a Tanh[r Sin[k (x - x0)]]+b

```

Assuming a and r are chosen not negative. By inspection, it is at a maxima when the Sin function is at +1, where it has a value of

```
b + a Tanh[r]

```

and a minima where the Sin function is at -1, where it has a value of

```
b - a Tanh[r]

```

Just for fun, I did this by the usual method of derivatives. I attach the notebook.

[Max Min 1.nb](https://community.wolfram.com/uploads/short-url/tNnNagT1IgEg5GX0BDAe9uSCaPQ.nb) (87.4 KB)
