Search code examples
matlabmatlab-figurebuilt-in

Why do MATLAB built-in function results differ from the ones i get when i define the function myself using the same expression?


I am currently doing spectral analysis of some signal in matlab and am supposed to use a Hamming window function (https://www.mathworks.com/help/signal/ref/hamming.html) for further analysis of the same signal but i am experiencing some unusual problem where i get the wrong result when i use a built in function hamming(L) and get the right result when i just write the function out myself the same way it is defined in MATLAB. Here is the code:

%This is a signal i am analyzing and it has N points.
F1 = 55/450;
F2 = 67/450;
N = 450;
n = 0:(N-1);
x = 50*cos(2*pi*F1*n)+100*cos(2*pi*F2*n)

% Here is the code for plotting the signal in N points
figure
n = 0:(N-1);
stem(n,x);
xlabel('n');
ylabel('x[n]');
title('Discrete Signal x[n]');
pause

% Here i am using a built in function. It is of length N, the same as x[n].
n=0:(N-1);
window1 = hamming(N);
figure
y1 = x.*window1; %The proper way of windowing a function.
stem(n, y1);
title('Windowed Discrete Signal y[n]');
pause
% This yields some nonsensical graph even though the window function itself graphs properly. 

% Here i looked at the expression on the site which is used for the built-in matlab function and wrote it myself.
n=0:(N-1);
window2 = 0.54-0.46*cos(2*pi*n./N);
figure
y2 = x.*window2;
stem(n, y2);
title('Windowed Discrete Signal y[n]');
pause
% Here it graphs everything perfectly.

Here is the image of the graph i am getting when writing the function myself: Proper Windowed Function And here is the one i get when i use a built in function: Nonsense Function

Conclusion is that i don't understand something about the way this works out when multiplying the signals out. Can you help me understand why and how should i modify the function to work out?


Solution

  • The problem is window1, returned by hamming, is a Nx1 vector while x is a 1xN vector. When you perform the element-wise multiplication on these it will produce a N*N matrix. See the example below. You will get the results you want if you reshape either window1 or x so that they match in shape (e.g. y1 = x.*window1';)

    >> a = [1 2 3]
    
    a =
    
         1     2     3
    
    >> b = [1; 2; 3]
    
    b =
    
         1
         2
         3
    
    >> a.*b
    
    ans =
    
         1     2     3
         2     4     6
         3     6     9