# Making a horizontal line of predefined length for a plot

28 views (last 30 days)
Iakovos Michail on 15 Nov 2022
Edited: Voss on 15 Nov 2022
I am trying to generate a line of a certain length, in this case from 0 to 2 using a variable. I need this line to have a constant value for that range.
In other words, something like this:
t = 0:0.1:2 ;
x(t) = 2;
plot(t,x)
This is however a part of a larger graph, the code below is the full program I am trying to implement:
t1 = -3:0.1:0;
t2 = 0:0.1:2;
t3 = 2:0.1:4;
t4 = 4:0.1:5;
x1 = cos(pi./t1);
x2 = 2;
x3 = t3-1;
x4 = t4+2;
plot(t1,x1)
hold on
plot(t2,x2)
plot(t3,x3)
plot(t4,x4)
where t2 is my variable and x2 the value I want to have on that range as a horizontal line. This will produce a graph which does not include the value of x2 but the rest function just fine. I haven't worked with MATLAB for a year now and only did some basics last time, so I am not quite sure what I am supposed to do to get my desired result here.

Voss on 15 Nov 2022
Edited: Voss on 15 Nov 2022
One way is to give plot the two endpoints of the line segment, i.e.:
plot([0 2],[2 2]) % (0,2) and (2,2) Another way - if you want it to be more consistent with the syntax of the other plot calls, which all involve calculating x from t - is to use a function that is identically 2.
t2 = 0:0.1:2;
x2 = 0*t2 + 2;
plot(t2,x2) Or generate a vector of 2's the same size as t2:
t2 = 0:0.1:2;
x2 = 2*ones(size(t2));
plot(t2,x2) Either of the last two ways would be useful if you want to include a data marker, since t2 is defined at every 0.1 increment (as oppsed to the first way, which only has two points (one at each end of the segment), so only two markers would show up).
t1 = -3:0.1:0;
t2 = 0:0.1:2;
t3 = 2:0.1:4;
t4 = 4:0.1:5;
x1 = cos(pi./t1);
x2 = 2*ones(size(t2));
x3 = t3-1;
x4 = t4+2;
plot(t1,x1,'x-')
hold on
plot(t2,x2,'.-')
plot(t3,x3,'^-')
plot(t4,x4,'o-') ### Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

R2022b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!