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!

回答 (1 件)

Victor Parry
Victor Parry 2019 年 11 月 18 日

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 件のコメント

Russell Niven
Russell Niven 2022 年 7 月 27 日
This is great! However, it breaks when you have a perfectly horizontal line, assuming since arctan(90)= undefined)
Torsten
Torsten 2022 年 7 月 27 日
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

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeSimscape Electrical についてさらに検索

質問済み:

2014 年 3 月 14 日

コメント済み:

2022 年 7 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by