How do I write a for loop to calculate the difference between two points?

조회 수: 9 (최근 30일)
S.
S. 2013년 10월 24일
편집: Randy Souza 2013년 10월 24일
Here's what I have so far:
% Write a program using a for loop to get user input for a nX2 array, then find the difference between point 1 and the rest.
n=input('how many points do you have? ');
A=zeros (n,2);
for row=1:n
for column=1:2
usernumber=input('enter a number: ');
A(row, column)=usernumber;
end
end
A
for row=1:length(A(n,2))
Dist=sqrt((A(n,1)-A(n+1,1))^2)+((A(n+1,2)-A(n,2))^2)
end
Dist
I'm not sure how to find the differences through the loop and then store them

채택된 답변

Andrei Bobrov
Andrei Bobrov 2013년 10월 24일
편집: Andrei Bobrov 2013년 10월 24일
Dist = zeros(size(A,1),1);
for jj = 2:numel(Dist)
Dist(jj) = sqrt(sum((A(jj,:) - A(1,:)).^2,2));
end
or
Dist = sqrt(bsxfun(@minus,A,A(1,:)).^2*[1;1]);
or
A1 = num2cell(bsxfun(@minus,A,A(1,:)),1);
Dist = hypot(A1{:});
  댓글 수: 3
S.
S. 2013년 10월 24일
편집: S. 2013년 10월 24일
thanks everyone for your help. Andrei's answer was the one that worked for my application.
S.

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

추가 답변 (2개)

Michael
Michael 2013년 10월 24일
Try using cell arrays by using something like:
for row =1:n
for col =1:2
dist{row,col} = ... %pythogrean thm
end
end
% Define, by hand, as it would be zero (I think)
dist{1,1} = 1;
Good Luck
  댓글 수: 1
S.
S. 2013년 10월 24일
so my distance formula:
d=sqrt((x2-x1)^2+(y2-y1)^2)
what would I call x2,x1, y2,y1? maybe row(n) and column(x)?
or would the for loop take care of the rows and columns?
thanks

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


Simon
Simon 2013년 10월 24일
Hi!
You store your entered user input in a matrix, say N. As you wrote N is of dimension n*2.
The distance of a point from the first one is like you wrote
d=sqrt((x2-x1)^2+(y2-y1)^2)
You can write a loop to calculate this
for p = 1:n
d(p) = sqrt((N(n,1)-N(1,1))^2+(N(n,2)-N(1,2))^2)
end
This gives you the distance from each point to the first one, with "d(0) = 0" of course.
  댓글 수: 1
Simon
Simon 2013년 10월 24일
One comment to my solution: try to avoid loops! Matlab is best used with matrix calculations. Rewrite the loop like this:
% create matrix as big as N, with only the first point in all lines
Nfirst = ones(n,1) * N(1,:);
% create the difference (in x and y) between all point to the first one
Ndiff = N - Nfirst;
% take the square of each difference (this is x^2 and y^2)
Nsquare = Ndiff.^2;
% sum along dimension 2 (this is x^2+y^2)
Nsum = sum(Nsquare, 2);
% take the square root
d = sqrt(Nsum)
Or write it in one row
d = sqrt(sum((N-(ones(n,1) * N(1,:))).^2, 2));

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by