Easiest way to create a line from 2 XY coordinates

조회 수: 1 (최근 30일)
Lina Koronfel
Lina Koronfel 2022년 2월 24일
댓글: Lina Koronfel 2022년 4월 1일
What is the fastest way or the best way to transfer these values to an array to obtain an output that is the distance between Point(X1,Y1) and Point(X2,Y2) for every iteration? The original data is 300,000 iterations, so I want to end up with a vector of 300,000 distance values
Iter X1 Y1 X2 Y2
0 125.1673584 13.18046188 194.4534607 176.9597931
1 126.4874725 13.56817341 196.5686646 176.3899078
2 125.1508484 13.18618774 196.9122314 175.5451508
3 125.8279877 12.93647861 195.5947876 176.2555695

채택된 답변

Scott MacKenzie
Scott MacKenzie 2022년 2월 24일
MATLAB's hypot function is probably your best bet:
M = [0 125.1673584 13.18046188 194.4534607 176.9597931;
1 126.4874725 13.56817341 196.5686646 176.3899078;
2 125.1508484 13.18618774 196.9122314 175.5451508;
3 125.8279877 12.93647861 195.5947876 176.2555695]
M = 4×5
0 125.1674 13.1805 194.4535 176.9598 1.0000 126.4875 13.5682 196.5687 176.3899 2.0000 125.1508 13.1862 196.9122 175.5452 3.0000 125.8280 12.9365 195.5948 176.2556
d = hypot(M(:,2)-M(:,4), M(:,3)-M(:,5))
d = 4×1
177.8320 177.2633 177.5109 177.5965
  댓글 수: 7
Walter Roberson
Walter Roberson 2022년 3월 29일
hypot is consistently slower than square root of sum.
The difference is that hypot has code in order to be able to give useful answers for cases where the squares would overflow to infinity or underflow to 0, and for those cases it can be very valuable. But if you are certain you will never encounter those cases then manual calculation is faster.
N = 20;
t1 = zeros(N,1); t2 = zeros(N,1);
M = [(1:300000)' rand(300000,4)];
for K = 1 : N; start = tic; d = hypot(M(:,2)-M(:,4), M(:,3)-M(:,5)); stop = toc(start); t1(K) = stop; end
for K = 1 : N; start = tic; d = sqrt((M(:,2)-M(:,4)).^2 + (M(:,3)-M(:,5)).^2); stop = toc(start); t2(K) = stop; end
plot([t1, t2])
legend({'hypot', 'sqrt sum'})
Lina Koronfel
Lina Koronfel 2022년 4월 1일
Thank you for explaining. I got my answer :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by