Pdist2 inside for
Show older comments
Hi everybody,
i have two 3D matrix A and B with different lengths. I need to build a for loop to calculate the pdist2 between the first row of A and all the rows of B, the second row of A and all the rows of B, ...., the n row of A and all the rows of B.
An example of the two matrix:
A
X Y Z
0.2 0.4 0.5
1.4 0.6 4.5
0.3 0.5 3.1
B
X Y Z
0.8 0.7 0.5
1.4 0.9 1.5
0.2 3.5 2.1
0.3 0.7 0.5
2.4 0.3 0.5
0.2 3.5 3.1
Thank you very much!
Accepted Answer
More Answers (1)
Star Strider
on 16 Jan 2019
No loop needed, since pdist2 does it all for you:
A = [0.2 0.4 0.5
1.4 0.6 4.5
0.3 0.5 3.1];
B = [0.8 0.7 0.5
1.4 0.9 1.5
0.2 3.5 2.1
0.3 0.7 0.5
2.4 0.3 0.5
0.2 3.5 3.1];
D = pdist2(A,B);
fprintf(1, 'B:\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n',1:size(B,1))
fprintf(1, 'A:%d\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n', [(1:size(A,1))' D]')
A1B2 = sqrt((A(1,:)-B(2,:))*(A(1,:)-B(2,:))'); % First Row Of A, Second Row Of B
A3B6 = sqrt((A(3,:)-B(6,:))*(A(3,:)-B(6,:))'); % Third Row Of A, Sixth Row Of B
The ‘proof’ is in the last two lines, that show those distances.
Categories
Find more on Resampling Techniques in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!