MATLAB: Margin() returns incorrect gain margin for open-loop unstable system

Control System Toolboxgain marginMATLABr2014a

I am wondering if anyone knows why MATLAB returns an incorrect value for gain margin when using margin() with a system that is open-loop unstable, or whether this is a bug that should be reported.
See the following example:
>> Gol1
Gol1 =
0.00074321 (z+0.9875)
---------------------
(z-1.001) (z-0.9619)
Sample time: 0.04 seconds
Discrete-time zero/pole/gain model.
>> [Gm,Pm,Wgm,Wpm]=margin(Gol1)
Gm =
0.0316
Pm =
48.7296
Wgm =
0
Wpm =
0.7615
Manually applying the Jury stability criterion to the above discrete-time system results in a range of stability of 0 < K < ~50.6. margin(), on the other hand, returns a gain margin of -30dB/0.0316 at 0 rad/s for some reason.
The bode plots generated using margin() or bode() clearly shows the -180deg phase crossover near ~6.8 rad/s with ~34dB of gain margin, which is the correct result. Why does margin() return the wrong Gm and Wgm values?

Best Answer

I don't agree that "MATLAB returns incorrect value". If you read the documentation for margin , you will see the section I posted below as an image (at the very end of the answer). Notice the text I highlighted in yellow. The important thing here is that margin returns minimum gain margin, i.e., if the phase is -180 at several frequencies, the answer is for the frequency where the gain margin is the lowest.
Now take your system and evaluate gain and phase at w = 0 rad/sec:
This shows that at 0 rad/sec the phase is -180, and gain is 31.7 dB (ignore small numerical differences with your 30db) - so the answer that margin returns.
If you want to get not just the minimal gain margin, but all of them, use allmargin :
You see that this system has 3 gain margins, and margin returned the lowest one, as intended.