What does xlim() do in my code and why are its brackets empty?

11 views (last 30 days)
Hey guys,
I like adding a straight horizontal line at y = 0 to my plots therefore I am using the code shown below. It's working perfectly for my purposes so there is no need to change anything.
plot(x, z);
line(xlim(), [0,0], 'LineWidth', 1, 'Color', 'k', 'LineStyle','--');
grid on;
xlabel('This is the label for the x-axis')
ylabel('This is the label for the y-axis')
Since I found this code on the internet I am wondering what xlim() does in my code and why its brackets are empty?
Is there something generell to say about the function of empty round brackets () ?
Thanks for your help,
Best,
Sven
  1 Comment
Stephen23
Stephen23 on 7 May 2021
"Is there something generell to say about the function of empty round brackets () ?"
Sure: that function is being called without any inputs.
The xlim documentation clearly shows that xlim accepts zero or more input arguments.
Note that your code would be simplfied by using yline.

Sign in to comment.

Accepted Answer

KSSV
KSSV on 7 May 2021
Edited: KSSV on 7 May 2021
xlim()
The above takes the x-values based on the plot/ the input x you give. It will draw a line along x-axes in the range as the y-valyes are given to be zero.
Instead like givn, you can also use:
line([min(x) max(x)], [0,0], 'LineWidth', 1, 'Color', 'k', 'LineStyle','--');
  3 Comments
Sven Krasel
Sven Krasel on 7 May 2021
Hey KSSV,
I have another question. According to my 220x1 double my x-range is from 0 to 1095 but my line goes from 0 to 1200.
Why does xlim() doesn't recognize this range? When I type [0, 1095] instead of xlim() it works as I expect it to.
Thanks,
Sven
Image Analyst
Image Analyst on 7 May 2021
That's not exactly right - that it goes from the min x to the max x. The graph goes from a left number that is "nice" to a right number that is "nice". So if your x goes from 1.34 to 117.123, xlim might make your graph go from 0 to 120 and xlim() would return [0, 120] instead of [1.34, 117.123].
So the line command would go from 0 to 120.
The way they did that, while it still works, can be done much simpler now. Instead of drawing a line at y=0 along the x axis,
line(xlim(), [0,0], 'LineWidth', 1, 'Color', 'k', 'LineStyle','--'); % Old way - unnecessarily complicated.
you can use yline
yline(0, 'LineWidth', 1, 'Color', 'k', 'LineStyle','--'); % New way is simpler
yline() draws a horizontal line at the specified y value.
xline() draws a vertical line at the specified x value.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!