Borrar filtros
Borrar filtros

Why knnsearch () function slows down the code?

3 visualizaciones (últimos 30 días)
Sidra Aleem
Sidra Aleem el 3 de Abr. de 2017
Editada: Sidra Aleem el 4 de Abr. de 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 comentarios
Jan
Jan el 3 de Abr. de 2017
Slows down the code compared to what? Of course searching for groups costs some time.
Sidra Aleem
Sidra Aleem el 3 de Abr. de 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?

Iniciar sesión para comentar.

Respuestas (1)

Jan
Jan el 3 de Abr. de 2017
Editada: Jan el 3 de Abr. de 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 comentario
Sidra Aleem
Sidra Aleem el 4 de Abr. de 2017
Editada: Sidra Aleem el 4 de Abr. de 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;

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by