function to discretize a line between two points

8 views (last 30 days)
following are the two questions I have to do.
I did the first one and it does not look right. following is the code
function [points] = discretizeLine(p1, p2, stepsize)
dt = stepsize;
theta = atan2(p2(1,2)-p1(1,2),p2(1,1)-p1(1,1));
i_comp = dt * cos(theta);
j_comp = dt * sin(theta);
i=0;
while(1)
points(i+1,1) = p1(1,1) + i_comp * i;
points(i+1,2) = p1(1,2) + j_comp * i;
i = i+1;
if((abs(p1(1,1) + i_comp * i-p2(1,1)) < abs(i_comp))||(abs(p1(1,2)+j_comp*i-p2(1,2))<abs(j_comp)))
break;
end
end
end
please help me with these two questions thanks!

Answers (1)

Victor Parry
Victor Parry on 18 Nov 2019
just took me a few hours to answer this 5 yo question, but at least it works now.
function [points] = discretizeLine(p1, p2, stepsize)
dt = stepsize;
theta = atan2(p2(1,2)-p1(1,2),p2(1,1)-p1(1,1));
i_comp = dt * cos(theta);
j_comp = dt * sin(theta);
deltadist = [i_comp,j_comp];
i=0;
while(1)
points(i+1,1) = p1(1,1) + i_comp * i;
points(i+1,2) = p1(1,2) + j_comp * i;
i = i+1;
if(abs(p1+i*deltadist-p2)<=abs(deltadist)) %((abs(p1(1,1) + i_comp * i-p2(1,1)) < abs(i_comp))||(abs(p1(1,2)+j_comp*i-p2(1,2))<abs(j_comp)))
break;
end
end
end
  2 Comments
Russell Niven
Russell Niven on 27 Jul 2022
This is great! However, it breaks when you have a perfectly horizontal line, assuming since arctan(90)= undefined)
Torsten
Torsten on 27 Jul 2022
p0 = [0,0];
p1 = [1,1];
stepsize = 0.1;
t = (0:stepsize:1).';
points = [(1-t)*p0(1) + t*p1(1),(1-t)*p0(2) + t*p1(2)]
points = 11×2
0 0 0.1000 0.1000 0.2000 0.2000 0.3000 0.3000 0.4000 0.4000 0.5000 0.5000 0.6000 0.6000 0.7000 0.7000 0.8000 0.8000 0.9000 0.9000

Sign in to comment.

Categories

Find more on Partial Differential Equation Toolbox 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!