首页 > 解决方案 > 如何制作从 a 点开始并在 b 点结束的斜坡函数。[a,b]。并且在区间外的值为 0

问题描述

我想构建一个从 a 点开始并在 b 点结束的斜坡函数。[a,b]

我已经构建了一个斜坡函数的代码,它从 0 开始并在点 b.[0,b] 结束。

这是代码:

hold on
b =2  % time in wich the ramp finish
a=1  %time in which the ramp start
t = [0:0.01:15]';  %timespan of the ramp function
for impAmp = [3 5 10]  %height of the ramp 
function
rampOn = @(t) t<=b;
ramp =@(t) t.*impAmp.*rampOn(t);
plot(t,ramp(t))
end

但我想定义区间 [a,b] 中定义的斜坡函数的新代码。并且在区间外的值为 0。

我试过这段代码。但它修改了所有的斜坡函数。

hold on
b =2 % time in wich the ramp finish
a=1 %time in which the ramp start
t = [0:0.01:15]';%timespan of the ramp function
for impAmp = [3 5 10]%height of the ramp function
rampOn = @(t) a<t<=b;
ramp =@(t) t.*impAmp.*rampOn(t);
plot(t,ramp(t))
end

标签: matlabfor-loopplot

解决方案


作为一个函数,你有:

function y=ramp(x,a,b,h)
    y = h/(b-a)*(x-a).*(x>a).*(x<b);
end

作为函数句柄,

f = @(x,a,b,h) h/(b-a)*(x-a).*(x>a).*(x<b);

无论哪种方式,定义参数ab高度h并根据需要使用函数:

a = 1; 
b = 4;
h = 7;
x = 0:0.1:5;
y = ramp(x,a,b,h);
plot(x,y)

a = 2; 
b = 2.5;
h = 10;
x = 0:0.1:5;
plot(x,ramp(x,a,b,h))

推荐阅读