MATLAB: Sqaure() does not adhere to duty cycle

cyclediscrete timedutyratesamplingSignal Processing Toolboxsquarewave

square() function does not adhere to duty cycle. The following code outputs waveforms with 50% and 60% duty cycle alternatively, while it should be 50%: 
>> fs = 1200; 
>> t = ((1:8192) – 1) / fs; 
>> square(2 * pi * 120 * t, 50) 
ans = 
Columns 1 through 37 
1 1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 1 -1 -1 -1 -1 -1 1 1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 1 -1 -1 
 

Best Answer

In your case, in each cycle there are 10 time samples (1200Hz/120Hz).  Thus, every 11th sample should be the first sample of the next cycle.  This is exactly what we have here, as seen in the attached figure, dutyCycle1200Hz.fig.  At the "crossover" point, which is between the 5th and 6th sample of the cycle, the 6th sample can either be 1 or 0, depending on the precision of the computer.  As the number of samples in each cycle increases, the discrete representation of the square wave approaches that of the actual continuous-time square wave, and the "cross-over" time becomes finer and finer.  Now, as there are only 10 samples to represent each cycle in this case, the representation is very coarse; the 6th sample point having value of +1 might give the impression that the duty cycle represented here is 60%, but in fact it is not the case.
To help you see this point, I have attached another duty cycle figure with the sample frequency of 120Hz and duty cycle of 50%, but this time sampled at 12KHz.  Now there are 100 time samples per cycle.  You can see that the square wave overall exhibits a duty cycle of 50%.  If you look carefully at the transition point that is between the 50th and 51st sample point in each cycle, you can still observe what you are seeing with the 1200Hz case that there is one extra sample at +1 value for every other sample.  However, the duty cycle represented here is clearly 50%
In summary, the "square" function produces the square wave at the specified duty cycle with the specific sampling rate.  As the sampling rate increases, the output of the square wave vector approaches that of the continuous-time representation.  This is the sample principle behind the "plot" function in MATLAB.  If you wish to have the generated wave to approach the 50% duty cycle wave in continuous time, the solution here is to increase your sampling rate.