为什么 MATLAB 内置函数的结果与我使用相同表达式自己定义函数时得到的结果不同?

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

我目前正在 matlab 中对一些信号进行频谱分析,我应该使用 Hamming window 函数 (https://www.mathworks.com/help/signal/ref/hamming.html) 进一步分析同一信号,但我遇到了一些不寻常的问题当我使用内置函数 hamming(L) 时得到错误的结果,而当我按照在 MATLAB 中定义的方式自己编写函数时得到正确的结果。这是代码:

%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.

这是我自己编写函数时得到的图形图像: Proper Windowed Function 这是我使用内置函数时得到的: Nonsense Function

结论是,我不太了解将信号相乘时的计算方式。你能帮我理解为什么以及我应该如何修改函数来计算吗?

问题是 window1,由 hamming 返回,是一个 Nx1 向量,而 x 是一个 1xN 向量。当您对它们执行逐元素乘法时,它将产生一个 N*N 矩阵。请参见下面的示例。如果您重塑 window1x 以使它们的形状匹配(例如 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