how to find euclidean distance between training and test data?

4 次查看(过去 30 天)
I have two matrices A of size 2x5 and B of size 2x2 such that each column is a feature vector. I want to calculate the euclidean distance between A and B. i.e I want to calculate the euclidean distance between first column of B with every column of A and similarly need to calculate the second column of B with every column of A .
A=rand(5,2);
B=rand(2,2);
for i=1:2
for j=1:5
d=sqrt(B(i,:)-A(j,:));
end
end

采纳的回答

Walter Roberson
Walter Roberson 2018-10-19
Statistics toolbox:
d = pdist2(A.', B.');
pdist2 normally operates row by row, which is why the .' are there, to make your column-oriented data into row-oriented data.
  2 个评论
kitty varghese
kitty varghese 2018-10-19
Im getting an error.
Error using pdist2 (line 138)
X and Y must have the same number of columns.
Walter Roberson
Walter Roberson 2018-10-19
Your problem statement says,
I have two matrices A of size 2x5 and B of size 2x2
and that
each column is a feature vector.
But your sample code has
A=rand(5,2);
which is a 5 x 2 array, not a 2 x 5 array. The columns of your actual A are length 5, and the columns of your actual B are length 2, and it is not meaningful to find the euclidean distance between objects with different lengths.
Your sample code has
sqrt(B(i,:)-A(j,:))
which is comparing all of the columns of particular rows, which would be suitable for the case where the rows are feature vectors, not column vectors.
If your rows are feature vectors then pdist2(A, B)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Statistics and Machine Learning Toolbox 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by