# Calculation of gain margin fails

**URL:** https://discourse.julialang.org/t/calculation-of-gain-margin-fails/109819
**Category:** Modelling & Simulations
**Tags:** question, controlsystems
**Created:** [February 6, 2024, 4:29pm UTC](https://discourse.julialang.org/t/calculation-of-gain-margin-fails/109819 "2024-02-06T16:29:24Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![ufechner7](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ufechner7/32/51363_2.png) [@ufechner7](https://discourse.julialang.org/u/ufechner7)
#### Post date: [February 6, 2024, 4:29pm UTC](https://discourse.julialang.org/t/calculation-of-gain-margin-fails/109819/1 "2024-02-06T16:29:24Z")

</div>

I have the following code:

```julia
using ControlSystemsBase

Ts = 0.01
Ku = 100/5e6
K2 = 5e6
num = [Ku * Ts]
den = [1, -1]
P = tf(num, den, Ts) # plant
C = K2
sys = feedback(P, C)
ol_sys = P*C

margin(ol_sys)

```

If I create a bode plot of the open loop system, I can see a gain margin of 6dB and a phase margin of 60 degrees.

 ![Figure_1](https://global.discourse-cdn.com/julialang/original/3X/c/6/c6fb920114d0684b7b9b6fb8a0b91881d1c0ed23.png)

The margin(ol\_sys) command has the following output:

```julia
julia> margin(ol_sys)
(wgm = [NaN;;], gm = [Inf;;], wpm = [104.76061896928398;;], pm = [59.98829336940935;;])

```

In other words, it calculates the phase margin correctly, but it does not find any value  
for the gain margin.

Is this a bug in the `margin` function, or am I using it wrongly?

---

<div class="post-metadata">

### Author: ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)
#### Post date: [February 6, 2024, 4:42pm UTC](https://discourse.julialang.org/t/calculation-of-gain-margin-fails/109819/2 "2024-02-06T16:42:46Z")

</div>

Notice that the phase curve never crosses -180 degrees, so the margin command is slightly confused. You can evaluate the margin exactly at the Nyquist frequency

```julia
julia> margin(ol_sys, [100pi])
(wgm = [314.1592653589793;;], gm = [2.0;;], wpm = [NaN;;], pm = [Inf;;])

```

Gain and phase margins are primitive measures of robustness, I’d consider using the diskmargin instead

```julia
plot(RobustAndOptimalControl.diskmargin(ol_sys))

```

![image](https://global.discourse-cdn.com/julialang/original/3X/8/b/8b9b326b2533cfc7483cd660e3b2c2c2746d7075.png)

* * *

Here’s a PR fixing margin in this case

> <https://github.com/JuliaControl/ControlSystems.jl/pull/915>
