How to use a function for multiple sets of numbers with a single command?

For instance, I created a function to calculate the distance between 2 points with X,Y coordinates with this formula:
D=sqrt((X1-X2)^2+(Y1-Y2)^2)
Point nb. X Y
and I have this matrix: A = 1 2800 3500
2 4200 5300
3 5100 6200
- - -
- - -
n x y
The dimension of matrix A is ,,n" rows and 2 columns
Now, how I can apply this function to calculate distances between points 1&2, 2&3, 3&4 and so on, with a single command?Is it possible?
*Note: English is not my first language, and I may have not been very explicit

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2013년 4월 3일
편집: Andrei Bobrov 2013년 4월 3일
k = diff(A);
D = hypot(k(:,1),k(:,2)); % I am corrected after Sean's comment.
On Ciuban's comment.
Try used function pdist from Statistics Toolbox:
A = [2800 3500
4200 5300
5100 6200];
D = pdist(A);

댓글 수: 4

Its working. You are very helpful guys, thank you very much. 1 more thing I want to discuss. Now, its possible to make this function calculate every combination of points? At the moment it calculates distances between 1&2, 2&3, 3&4 and so on. What I need to do to make that command calculate 1&4, 2&4 and every combination possible? Once again, thank you very much for your help
Look at my answer and where ever you see A(2:end) and A(1:end) changes how far you want to go.
For example, if you want 1&4 and 2&4, you would use A(4:end) and A(2:end-4) respectively. Try to explore the colon operator and see what it does. For example, try the following
A=[1 2 3; 4 5 6; 7 8 9];
A(1:2:end, 1)
A(1:3:end)
A(1, 1:2:end)
A(1:3,1)
Ciuban, if you want every combination, it sounds like you want to calculate the inter-point distance matrix. This can get very memory-intensive if done poorly/naively, so I'd recommend using one of the File Exchange solutions for this. I'd recommend:
href = ""<http://www.mathworks.com/matlabcentral/fileexchange/18937-ipdm-inter-point-distance-matrix</a>>

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

추가 답변 (1개)

Mahdi
Mahdi 2013년 4월 3일
편집: Mahdi 2013년 4월 3일
D=sqrt((A(2:end,2)-A(1:end-1,2)).^2+(A(2:end,3)-A(1:end-1,3)).^2)

댓글 수: 5

Thank you for your answer but after I put that command MatLab it shows me this error ,,Index exceeds matrix dimensions".
Is your matrix A as you've shown it? Or is it only 2 columns?
What are the dimensions of A? Based on your example, it is a bit unclear.
the dimension of A is ,,n" rows and 2 columns
Then you can just modify Mahdi's code as:
D=sqrt((A(2:end,2)-A(1:end-1,2)).^2+(A(2:end,1)-A(1:end-1,1)).^2)

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

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by