Operate on Successive Values Without Loops

조회 수: 9 (최근 30일)
David
David 2012년 5월 1일
Say I have a vector of x values, and a vector of y values. I would like to write a function to calculate the distance between successive points. I know how to do this in a loop, like the snippet given below.
for i = 1:1:size(x) - 1
distance(i) = sqrt((x(i) - x(i + 1)) ^ 2 + (y(i) - y(i + 1)) ^ 2)
end
Is there a way to do this without the loop?

채택된 답변

Kye Taylor
Kye Taylor 2012년 5월 1일
Totally... first arrange your vectors as column vectors, then try
distance = sum(sqrt((x(1:end-1)-x(2:end)).^2 + (y(1:end-1)-y(2:end)).^2),2);
  댓글 수: 2
David
David 2012년 5월 1일
Great! Except for the sum(), this was exactly what I needed.
Kye Taylor
Kye Taylor 2012년 5월 1일
Haha, right... no sum :)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by