already know function: find x value given y AND plot (x,y) on the same graph

Can someone help me with this simple question? I already know the function expression. I would like to find the x value corresponding to y=0.37 and plot the point (x,y) with dash lines connecting to x/y axis in the same graph on top of the line for y?
Here is my current code:
x = 0:100000;
y = exp(-x/38190.7);
figure
semilogy(x,y)
grid on
Thank you!

 Accepted Answer

This works:
x = 0:100000;
ofst = 0.37;
y = @(x) exp(-x/38190.7); % Create Anonymous Function
xval = fzero(@(x) y(x)-ofst, 1) % Solve For ‘ofst’ Value
figure(1)
plot(x, y(x))
hold on
plot([xval xval], [0 ofst], '--')
plot([0 xval], [ofst ofst], '--')
plot(xval, ofst, 'bp')
hold off
grid

5 Comments

Hi, thank you very much for the answer! When I changed plot(x, y(x)) to semilogy(x, y(x)) the dash line connecting to x-axis disappeared. Do you know how to fix this?
My pleasure!
The reason is the log of zero is -Inf, so the zero didn’t plot. The fix was to change the zero to min(ylim) in the first plot call in the hold block.
This works:
x = 0:100000;
ofst = 0.37;
y = @(x) exp(-x/38190.7); % Create Anonymous Function
xval = fzero(@(x) y(x)-ofst, 1) % Solve For ‘ofst’ Value
figure(1)
semilogy(x, y(x))
hold on
plot([xval xval], [min(ylim) ofst], '--')
plot([0 xval], [ofst ofst], '--')
plot(xval, ofst, 'bp')
hold off
grid
When you have
plot([0 xval], [ofst ofst], '--')
then that first one has x = 0. You have a log plot so log(0) is the left coordinate. And log(0) is -infinity . MATLAB never draws lines when the coordinate is infinite. You need to change that 0 to some positive value. Likewise in the other plot() line.
The code works fine. Can you please elaborate the code
plot([xval xval], [min(ylim) ofst], '--')
plot([0 xval], [ofst ofst], '--')
plot(xval, ofst, 'bp')
MATLAB requires two values for the x and two values for y in order to plot the line. It will plot a constant line at a given x or y if both values of either the x or y coordinates are the same value.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!