function to discretize a line between two points

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!

Risposte (1)

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 Commenti

This is great! However, it breaks when you have a perfectly horizontal line, assuming since arctan(90)= undefined)
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

Accedi per commentare.

Categorie

Scopri di più su Simscape Electrical in Centro assistenza e File Exchange

Richiesto:

il 14 Mar 2014

Commentato:

il 27 Lug 2022

Community Treasure Hunt

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

Start Hunting!

Translated by