필터 지우기
필터 지우기

Why knnsearch () function slows down the code?

조회 수: 3 (최근 30일)
Sidra Aleem
Sidra Aleem 2017년 4월 3일
편집: Sidra Aleem 2017년 4월 4일
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;

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by