matlab中的矩形函数

信息处理 matlab
2022-01-28 19:23:34

我正在尝试编写此函数:g(t)=rect(t/T)f(t)

我接受:并且我知道如何编程t=0:1:20f(t)

但是我对矩形函数有疑问。如何在matlab中编写这个函数?

4个回答
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 搜索路径中。

有很多方法

使用内联函数

clear all
x=linspace(-1,1,1024);
rect=@(x) (sign(x+.5)-sign(x-.5))/2
plot(x,rect(x))
title('rect')
xlabel('x')

在此处输入图像描述

rect(t/T) 留作练习(给一个人一条鱼,你喂他一天,教他钓鱼,他就有借口离开家门)

如果您知道如何编程任何功能f(t), 那么你应该知道如何编写一个特定的函数 rect(t/T).

但是,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()是可以执行此操作的内置函数。