如何在 MATLAB 中绘制拆分函数

how to plot split function in MATLAB

我正在尝试在 MATLAB 中绘制一个图形,它具有两个采用不同域的函数。

f1(t) = 50*t              % 0<=t<15
f2(t) = 160/3)*t - 180    % 15<=t<=60

我尝试使用下面的方法

t1 = 0:15;
y = f1(t1)
plot(t1,y)
hold on

t2 = 15:60 ;
y = f2(t2)
plot(t2,y)
hold off

然后我得到两个不形成连续线的图表。 the graph from the above code

我需要从 (15,750) 开始的红色图表 我可以作弊并将第二张图的起点移动到 (15,750) 但是有没有一种方法可以将它们绘制成一个函数?

两种方法。使用循环和不使用循环。

f1 = @(t) 50*t              % 0<=t<15
f2 = @(t) 160/3*t - 180    % 15<=t<=60

t = 0:60 ; 
f = [f1(t(t<15)) f2(t(t>=15))] ;
plot(t,f)

有循环

f1 = @(t) 50*t              % 0<=t<15
f2 = @(t) 160/3*t - 180    % 15<=t<=60
f = zeros(size(t)) ;
for i = 1:length(t)
    if t(i) < 15
        f(i) = f1(t(i)) ;
    else
        f(i) = f2(t(i)) ;
    end
end
plot(t,f)

一个选项是定义单个函数,其中每个项乘以 t 的条件,在不适用时有效地将其清零

f = @(t) (50*t).*(t<15) + ((160/3)*t - 180).*(t>=15);

t = 0:60;
plot( t, f(t) );

如果您的函数很复杂,那么这可能会变得有点难以阅读,但它很紧凑。

我意识到我需要统一域。

%setting domain t (0 <= t <15 and 15 <= t)
t = [0:30]; %suppose match time is 30 seconds

t1 = t(1:16);
t1(numel(t)) = 0; %f1 takes t1 as domain (0 <= t < 15):array 17-31 is filled with 0

t2 = t(16:31);
t2 = [zeros(1, max(0, 15)), t2];  %f2takes t2 as domain (15 <= t):array 1-16 is filled with 0
t2(1:16) = 15;   %array 0-16 is filled with 15, to cancel (t-15) in the function 

f= f1(t1) + f2(t2); %Moira's dmg from two domains are added to form one data set

plot(t,f, 'm--') %plotting f 

我认为我仍然需要正确设置我的域。 该图看起来不像它应该的样子哈哈哈