How to draw perpendicular line from scatter points in 2-D plot
Show older comments
hold on
x=[0:0.02:2]
y=sin(x.^3 - 2)
plot(x,y,'k')
a=randperm(length(x),10);
b=x(a)
z=sin(b.^3 - 2)
scatter(b,z)
i have used this code to plot a line and get 10 random scatter points on it, now i need to make perpendicular lines from those scatter points onto the x and y axis, how do i do that
Accepted Answer
More Answers (1)
I would STRONGLY recommend you learn to use descriptive variable names. a? b? z?
MATLAB does not charge more for you to use two or, god forbid, even three letter names. Even more are possible, or so I hear. But the use of descriptive variable names will make your code possible to debug, when your code becomes longer and far more complex.
hold on
x=[0:0.02:2];
y=sin(x.^3 - 2);
plot(x,y,'k-')
a=randperm(length(x),10);
b=x(a);
z=sin(b.^3 - 2);
scatter(b,z)
I have no idea why you selected points as you did, as there are far easier ways to generate points randomly from an interval. (Read the help for rand.) But consider what this would do:
my_x = rand(1,10)*2;
But now, you want to generate WHAT perpendicular? Perpendicular lines to the curve? Or do you want to drop line segments from those points that are perpendicular to the x axis? Both are pretty easy, but the latter is trivial.
figure
plot(x,y,'k-')
hold on
scatter(b,z);
plot([b;b],[-ones(size(z));z],'-r')
Categories
Find more on Annotations 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!

