Plot questions (variables at legend, labeling a marker)

3 views (last 30 days)
hi , so i got two questions. i made a function to find an intersection between two lines (y=x+c) and then plots the lines. Now i have two questions, 1)how do i make the leggend accept the input variables to display. 2) how do i label the intersection point on the plot itself?
function p=inters(v1,v2) %v1,v2 are lines inputed as vectors i.e v1=[2 -1] v2=[-3,1] (y=2x-1,y=-3x+1)
xt=v1(1)-(v2(1));
c=v1(2)-(v2(2));
x0=(-c)/xt;
y0=v1(1)*x0+v1(2);
p=[x0,y0];
x=x0-5:x0+5;
xmarkers=x0;
ymarkers=y0;
plot(x,polyval(v1,x),'b',xmarkers,ymarkers,'b*')
hold
plot(x,polyval(v2,x),'g')
i need the legend to change depending on the input to the fuction v1 and v2 so me typing legend y=2x-1 wont work...

Accepted Answer

Star Strider
Star Strider on 26 Jan 2015
To label the intersection, use the text function, for example:
text(x0+0.1, y0+0.1, sprintf('Intersection at (%.3f, %.3f)', x0, y0))
Do something similar with the legend text:
lgndtxt1 = sprintf('y = %.3f X %+.3f', v1);
lgndtxt2 = sprintf('y = %.3f X %+.3f', v2);
legend(lgndtxt1, lgndtxt2, 'Location', 'NE')
You will have to experiment with this to get the result you want.
  2 Comments
Alex
Alex on 26 Jan 2015
this works well exept the part where it legends my marker instead of the second line. any way for it to ignore markers in legend ?
Star Strider
Star Strider on 26 Jan 2015
The easiest way to do that is to simply rearrange the plot statements and not have a legend entry for the markers.
The last few lines of your code then become:
. . .
xmarkers=x0;
ymarkers=y0;
plot(x,polyval(v1,x),'b')
hold
plot(x,polyval(v2,x),'g')
plot(xmarkers,ymarkers,'b*')
lgndtxt1 = sprintf('y = %.3f X %+.3f', v1);
lgndtxt2 = sprintf('y = %.3f X %+.3f', v2);
legend(lgndtxt1, lgndtxt2, 'Location', 'NE')

Sign in to comment.

More Answers (0)

Categories

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

Community Treasure Hunt

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

Start Hunting!