Plotting piecewise function

只愿长相守 提交于 2019-12-02 08:03:26

问题


I have a solution to a differential solution but the issue is that I have different solutions in different intervals.

For examle:

x_1(t) when t belongs to [0,t_1]  
x_2(t) when t belongs to [t_1,t_2]  
x_3(t) when t belongs to [t_2,t_3]

Now I need to plot these graphs so that they look like they have a single function i.e just immediately after the first graph x_1(t) until t_1, I need the other graph x_2(t) and so on.

Is it possible in Matlab?


回答1:


You can use plot with multiple inputs to plot them altogether:

% the functions:
x_1 = @(t) 2.*t;
x_2 = @(t) 5.*t;
x_3 = @(t) 7.*t;
% the transition points:
t_1 = 30;
t_2 = 60;
t_3 = 90;
% plotting:
plot(0:t_1,x_1(0:t_1),t_1:t_2,x_2(t_1:t_2),t_2:t_3,x_3(t_2:t_3))

Another way, that lets you define all kind of function specific visual properties is to use hold:

f = @(t,a) a.*t;
t = 0:30:100;
m = 'os^'; % choosing different marker for each function
for k = 1:numel(t)-1
    plot(t(k):t(k+1),f(t(k):t(k+1),k),m(k))
    hold on
end
hold off



来源:https://stackoverflow.com/questions/45435923/plotting-piecewise-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!