Why knnsearch () function slows down the code?

1 次查看(过去 30 天)
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 个评论
Jan
Jan 2017-4-3
Slows down the code compared to what? Of course searching for groups costs some time.
Sidra Aleem
Sidra Aleem 2017-4-3
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?

请先登录,再进行评论。

回答(1 个)

Jan
Jan 2017-4-3
编辑:Jan 2017-4-3
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 个评论
Sidra Aleem
Sidra Aleem 2017-4-4
编辑:Sidra Aleem 2017-4-4
@ 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;

请先登录,再进行评论。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by