function square = makesquare2(f,sf,amp,dur) % function square = makesquare2(f,sf,amp,dur) % Creates the timbre of a square wave by adding odd harmonics % with a magnitude proportional to the inverse of the harmonic number % ( a true square wave would contain an infinite number of odd harmonics) % The square wave generator has a built in smart feature that does not allow % it to cause aliasing when adding the upper harmonics. % Josh Arnold Decemebr 9,2004 % Modified by S. Scott Moor, Septemember 2005 % % Inputs: f = note frequency (Hz) % sf = sampling frequency (Hz) % amp = relative amplitude of the note (must be between 0 and 1) % dur = duration of note (seconds) % Output: square = the wave series for the notes % hnum = number of the highest harmonic to add % t = the time series for the note % num = the current number of the harmonic % harmonic = the harmonic to be added to the series % initialize values hnum = 9; t = 0:1/sf:dur; square = sin(2*pi*f*t); num = 3; % start adding harmonics above the fundamental %loop until all harmonics are created while(num < hnum ) if(num*f)<(sf/2) % Anti-aliasing safeguard - throws out harmonics above the Nyquist frequency harmonic = ((1/num)*amp)*sin(2*pi*(f*num)*t); else harmonic = 0*amp*sin(2*pi*(f*num)*t); end square = square + harmonic; num = num +2; end %scale the wave's ampliude values to 0 -> amp (the provided amplitude) square = amp*(1/max(abs(square)))*square;