我正在尝试编写此函数:
我接受:并且我知道如何编程。
但是我对矩形函数有疑问。如何在matlab中编写这个函数?
我正在尝试编写此函数:
我接受:并且我知道如何编程。
但是我对矩形函数有疑问。如何在matlab中编写这个函数?
function y = rect(x);
x = abs(x);
if x == 0.5
y = 0.5;
else
if x < 0.5
y = 1;
else
y = 0;
end
end
end
把它放在一个文件中并命名为"rect.m"。确保它在您的 MATLAB 搜索路径中。
如果您知道如何编程任何功能, 那么你应该知道如何编写一个特定的函数 .
但是,Matlab 已经为此提供了一个方便的函数 ,window.m您可以根据需要对其进行填充:
N = 65;
w = window(@rectwin ,N);
但更有趣的是在 Matlab 中使用有趣的功能,包括@内联函数的函数句柄,以及 function linkaxes.m,以轻松测试不同的选项(对于离散信号,矩形函数的不同版本并存):
% Choose among four types of discrete rectangular windows
time = (-20:20)'; T = 5;
f = @(t) sin(2*pi*t/30);
nCase = 4;
for iCase = 1:nCase;
switch iCase
case 1
%% Option 1: rectangular is defined as one on ]0,1[
w = @(t) ((t > 0) & (t < 1));
case 2
%% Option 2: rectangular is defined as one on [0,1]
w = @(t) ((t >= 0) & (t <= 1));
case 3
%% Option 3: rectangular is defined as one on ]-1/2,1/2[
w = @(t) (abs(t) < 1/2);
case 4
%% Option 4: rectangular is defined as one on [-1/2,1/2]
w = @(t) (abs(t) <= 1/2);
end
h1(iCase)=subplot(nCase,2,2*(iCase-1)+1) ;
plot(t,[f(t) w(t/T)],'x-')
legend('f','w')
h2(iCase)= subplot(nCase,2,2*(iCase-1)+2);
plot(t,[f(t).*w(t/T)],'o-')
legend('f \times w')
linkaxes([h1,h2],'xy')
end
一个结果如下所示:
rectangularPulse()并且triangularPulse()是可以执行此操作的内置函数。