Euclidean distance between two structs for nearest neighbour
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi all,
I am trying to do nearest neighbour between a set of images and a nearest neighbour model. However in my euclidean distance function I am getting errors suh as "matrix dimensions must agree".
As you can see i've attemped different ways but what im trying to do for these two functions is:
• Calculate the Euclidean distance between the test sample and all the training samples d(𝑠𝑎𝑚𝑝𝑙𝑒1,𝑠𝑎𝑚𝑝𝑙𝑒2)=|𝑠𝑎𝑚𝑝𝑙𝑒1−𝑠𝑎𝑚𝑝𝑙𝑒2|=√(𝑠𝑎𝑚𝑝𝑙𝑒1(1)−𝑠𝑎𝑚𝑝𝑙𝑒2(1))2+ (𝑠𝑎𝑚𝑝𝑙𝑒1(2)−𝑠𝑎𝑚𝑝𝑙𝑒2(2))2+⋯+(𝑠𝑎𝑚𝑝𝑙𝑒1(𝑛)−𝑠𝑎𝑚𝑝𝑙𝑒2(𝑛))2
• Select the closest training example
• Assign the closest training example’s label to the test image
function dEuc = EuclideanDistance(sample1,sample2)
% dEuc = sqrt(sum((sample1 - sample2).^2));
% dEuc = norm(sample1 - sample2);
% for i = length(sample1)
% for j = length(sample2)
% num = sum((sample1(:) - sample2(:)).^2);
% end
% end
% dEuc = sqrt(num);
% sample1 = repmat(sample1,1,size(sample2,2));
% dEuc = sqrt(sum((sample1(:)-sample2(:)).^2));
V = sample1 - sample2;
dEuc = sqrt(V .* V');
end
function prediction = NNTesting(testImage,modelNN)
dataset = modelNN.neighbours;
prediction = EuclideanDistance(testImage, dataset);
end
0 Kommentare
Antworten (1)
KSSV
am 9 Nov. 2020
Bearbeitet: KSSV
am 9 Nov. 2020
dEuc = sqrt(V .* V');
Replace the above with
dEuc = sqrt(sum(V.^2));
%% Demo
A = rand(100,2) ; B = rand(100,2) ;
dx = A-B ;
d = sqrt(sum(dx.^2,2)) ;
% Formula
d1 = sqrt((A(:,1)-B(:,1)).^2+(A(:,2)-B(:,2)).^2) ;
isequal(d,d1)
You have to use sum with 1 or 2 depending on your data is row major or column major.
6 Kommentare
Jason Reed
am 11 Nov. 2020
Ah, fair! Did he respond? I'm not exactly here because I figured this out haha
Siehe auch
Kategorien
Mehr zu Pattern Recognition and Classification finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!