Pdist2 inside for

8 views (last 30 days)
Riccardo Rossi
Riccardo Rossi on 16 Jan 2019
Edited: Jan on 17 Jan 2019
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

Jan
Jan on 16 Jan 2019
Edited: Jan on 16 Jan 2019
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 Comments
Riccardo Rossi
Riccardo Rossi on 17 Jan 2019
Edited: Riccardo Rossi on 17 Jan 2019
Thank's for answering.
Yes i was wrong, i mean 3D arrays. I need a loop because for each row wise result i have to put an "if" - "else if" statement.
So is it possible write a loop and process one array rowwise?
Thank you!
Jan
Jan on 17 Jan 2019
Edited: Jan on 17 Jan 2019
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.

Sign in to comment.

More Answers (1)

Star Strider
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.

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!