Leader

Saturday 6 April 2013

Alternative function: hann

Download
Explanation
The MATLAB Signal Processing toolbox has a function called HANN which generates a symmetric or periodic Hann window’s over a specified number of points. Implementing an alternative to this function is very simple and the equation is described here. Symmetric and periodic windows are the same length (specified by n), but a symmetric window starts and ends on 0, whereas a periodic window ends on the point before 0. 

This alternative Hann function produces the same output as the Matlab function where w is a column vector of length n. The second input is a string with the possible values 'symmetric' and 'periodic' If no second input is specified, it defaults to 'symmetric'.




Code run-through
This part of the code checks the number of input arguments using the NARGIN function:

if nargin == 1

b = 'symmetric';
end
If there's just one input it sets the second input to the default, b='symmetric'.

This part of the code checks if the second input (b) is set to 'periodic' or 'symmetric', then applies the appropriate equation:


if strcmp(b,'symmetric')

i = 1:n; w(i,1) = 0.5*(1-cos((2*pi*(i-1))/(n-1))); elseif strcmp(b,'periodic') i = 1:n; w(i,1) = 0.5*(1-cos((2*pi*(i-1))/(n))); else disp('Error') end
The STRCMP compares two strings and is the equivalent of a logical comparison such as a==b  but slightly faster when the two things being compared are strings. strcmp(b,'symmetric') where b='symmetric' returns a 1 and enters that part of the if statement, in the same way if b=='symmetric' would. If the second input is not 'periodic' or 'symmetric', an error is displayed by the code in the else statement, and nothing is done.

The two equations are vectorised i = 1:n; creates a vector, i, containing integer steps from 1 to the n specified. This is used as an index for w, at each point the equation is applied. For example:



>> w = hann2(5)
i = [1 2 3 4 5]
w(1,1) = 0.5*(1-cos((2*pi*(1-1))/(10-1)));
w(2,1) = 0.5*(1-cos((2*pi*(2-1))/(10-1)));
w(3,1) = 0.5*(1-cos((2*pi*(3-1))/(10-1)));
And so on...

This is a more efficient alternative to using a for loop, the following code would do the same thing (for a symmetric window, as above):

function w = hann3(n)


w=zeros(n,1);
for i = 1:n
w(i,1) = 0.5*(1-cos((2*pi*(i-1))/(n-1)));
end
This function loops through each value of i, up to n, one at a time.


Final code
function w = hann2(n,b)

if nargin==1
b='symmetric'; end if strcmp(b,'symmetric') i = 1:n; w(i,1) = 0.5*(1-cos((2*pi*(i-1))/(n-1))); elseif strcmp(b,'periodic') i = 1:n; w(i,1) = 0.5*(1-cos((2*pi*(i-1))/(n))); else disp('Error') end


No comments:

AdSense