简体   繁体   中英

Matlab not plotting function interval

I want to plot the following mathemathical function:

功能

I tried using the following code:

x= -3:0.1:3;
x1 = x(x>2 & x<2);
x2 = x(x==2)
y1 = (x1)+1
y2 = 2
plot([x1 x2], [y1 y2])

Why is it giving me an empty window?

It is not possible for the following conditional to ever be true since any number can't be simultaneously greater than and less than 2

x > 2 & x < 2

As a result, x1 is an empty vector and x2 is just going to be 2 , so your plotting command will just yield a single point at (2,2).

You want to use a logical or ( | ) instead

x1 = x(x > 2 | x < 2);

Also a better way to plot this would be the following

y = x + 1;          % Set all values to x + 1
y(x == 2) = 2;      % Replace those that meet your criteria

plot(x, y)

As a side note, it's generally a bad idea to use == to compare floating point numbers. You should instead use eps to check if two floating point numbers are equal:

y(abs(x - 2) < eps) = 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM