MATLAB: Square Wave Generation becomes inaccurate !

square wavesquare wave generation

Hi there! can someone help me please ? I have a problem with this here. When I generate the square wave after a while it becomes inaccurate! I need this Period:[1 1 1 1 -1 -1 -1 -1], N times. But it makes somewhere a mistake and I have after some Periods three times 1 or five times -1 and so on!
and I need help to make a square wave like this ->
Period:[1 1 -1 -1 -1 -1 1 1], N times, too.
Thanks a lot.
f_r=4;
spp = 8; % Samples per Period
N=1000;
t = 0:1/(spp*f_r):N-1/(spp*f_r); % (time)
f_Sq = 4;
A_Sq = 1;
W_Sq = floor(2*pi*f_Sq);
S_Sq = A_Sq*square(t*W_Sq);

Best Answer

The best square can do is to have the requested duty cycle that most nearly approximates that requested over the length of the series. 2*pi*f_Sq isn't going to be exact and using floor on it passing that to square will make it shorter than the average would otherwise be. The only way you can get an absolute repeat of N cycles of a given number of +/- values will be to either have the argument exact or to actually replicate the cycle N times and then scale that by a time duration.