Pdist2 inside for
조회 수: 1 (최근 30일)
이전 댓글 표시
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!
댓글 수: 0
채택된 답변
Jan
2019년 1월 16일
편집: Jan
2019년 1월 16일
Why? pdist2 works directly with providing a [M1 x N] and a [M2 x N] matrix. So why do you want to write a loop and process one matrix rowwise?
D = pdist2(A, B)
But you write "3D matrix". Maybe you mean "3D array", because matrices are 2D by definition. Then the shown examples are misleading. If A and B are 3D arrays, you for got to mention what you want to do with the 3rd dimension.
댓글 수: 2
Jan
2019년 1월 17일
편집: Jan
2019년 1월 17일
Yes, of course this is possible. Because I cannot know, what "put an "if" - "else if" statement" exactly means, I cannot post some explicit code. But I suggest to call pdist2 for the matrices. not for single rows, and use logical indexing to examine the results.
% Two 3D arrays, the 2nd dimension must be equal:
A = rand(5, 3, 2);
B = rand(10, 3, 7);
for iA = 1:size(A, 3)
for iB = 1:size(B, 3)
D = pdist2(A(:, :, iA), B(:, :, iB));
match = (D > 0.4); % Or whatever you need
...
end
end
Note: You neither posted the correct input, nor explained, what you want as output, nor asked a question, nor mentioned, what should be computed actually. This makes it hard to help you. Sorry, if my bold guesses are confusing only.
추가 답변 (1개)
Star Strider
2019년 1월 16일
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.
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!