Question

I need to search the nearest 3 neighbors to my sample data. My code is the following:

Sample = vec_1;      

Training = [vec_2;vec_3;vec_4;vec_5;vec_6];

IDX = knnsearch(Training,Sample,'K',3);

disp('Results: ');
disp (IDX);

I got:

Results: 
     5     3     2

My question is this: I want to assign image to each value:

for example for 5, img1.jpg
            for 3, img2.jpg........ so on
Was it helpful?

Solution

Construct a cell array of images where you can access the image by the particular index from KNN. You don't need to use the actual vector itself. The index can be used as the key instead.

Do something like the following:

 maxIndex = max(IDX);
 imgCellArray = cell(1, maxIndex);
 imgCellArray{IDX(1)} = img1;
 imgCellArray{IDX(2)} = img2;
 imgCellArray(IDX(3)} = img3;

Therefore, if IDX = [5 3 2], then the above code will allow you to access images in the way you wanted. imgCellArray{5} will give you img1, and is located at index 5, imgCellArray{3} will give you img2 and is located at index 3 and so on.

Bear in mind that there will be some empty slots in your cell array that haven't been populated. In particular, at locations 1 and 4. However, with regards to memory you shouldn't be too concerned as very little memory is allocated (if at all... I'm not quite sure here) to represent the empty cell.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top