Why knnsearch () function slows down the code?

3 visualizzazioni (ultimi 30 giorni)
Sidra Aleem
Sidra Aleem il 3 Apr 2017
Modificato: Sidra Aleem il 4 Apr 2017
I have to make feature vector in which I have to store distance between a candidate feature point and its four neighboring feature points. I am using knnsearch() for this purpose. However it slows down the code. How can I improve this?
Below is my code.
N = sum(cn_image(:) == 1) + sum(cn_image(:) == 3) + sum(cn_image(:) == 4); %Number of rows in feature Matrix
featr_vect = zeros(N,8);
for i = 1:size(cn_image,1)
for j = 1 : size(cn_image,2)
if (cn_image(i,j) == 1) || (cn_image(i,j) == 3) || (cn_image(i,j) == 4)
[Idx D] = knnsearch(cn_image(:), cn_image(i,j), 'k', 4, 'distance, 'euclidean');
end
end
end
  2 Commenti
Jan
Jan il 3 Apr 2017
Slows down the code compared to what? Of course searching for groups costs some time.
Sidra Aleem
Sidra Aleem il 3 Apr 2017
i am not talking from the perspective of comparison with some method. I want to speed up my code . is there any way for this?

Accedi per commentare.

Risposte (1)

Jan
Jan il 3 Apr 2017
Modificato: Jan il 3 Apr 2017
Currently your code overwrites Idx and D in each iteration. This is a massive waste of time. If only the last classification is wanted:
index = find(ismember(cn_image(:), [1, 3, 4]), 1, 'last');
[Idx D] = knnsearch(cn_image(:), cn_image(index), 'k', 4, 'distance, 'euclidean');
If the overwriting of Idx and D appears in the code posted here only and not in the real code: Please post the relevant part of the code. Such abbreviations are misleading frequently.
Optimizing code is hard, when the readers cannot run it. Better post some relevant input data, such that we can check our suggestions.
  1 Commento
Sidra Aleem
Sidra Aleem il 4 Apr 2017
Modificato: Sidra Aleem il 4 Apr 2017
@ Jan Simon I have to calculate the distance among four nearest neighbors. I do not have to overwrite them. At the moment I am trying to save the index of four nearest neighbors in a matrix of (N,4) as shown below in my code. So later i can use these index to calculate euclidean distance. However it is taking a lot f time for storing index.
N = sum(cn_image(:) == 1) + sum(cn_image(:) == 3) + sum(cn_image(:) == 4); %Number of rows in feature Matrix
featr_vect = zeros(N,4);
tic;
n =1;
for i = 1:size(cn_image,1)
for j = 1 : size(cn_image,2)
if (cn_image(i,j) == 1) || (cn_image(i,j) == 3) || (cn_image(i,j) == 4)
Idx = knnsearch(cn_image(:), cn_image(i,j),'k', 4);
for m = 1 :4
featr_vect(n,m) = Idx(m); % Saving index location
end
n = n +1;
end
end
end
tom=toc;

Accedi per commentare.

Community Treasure Hunt

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

Start Hunting!

Translated by