File Exchange

image thumbnail


version 1.4 (584 KB) by

A kd-tree mex lib which allows for nearest neighbor, k-nearest neighbor, range and ball queries

20 Ratings



kdtree provides a minimalistic implementation of kd-tree. The implementation can be used either inside MATLAB by means of MEX calls, or as a standalone tool, directly from a C/C++ program. The image on the website has been creaed with "fulltest.m"
This implementation offers the following functionalities:
- kdtree_build: k-d tree construction O( n log^2(n) )
- kdtree_delete: frees memory allocated by kdtree
- kdtree_nearest_neighbor: nearest neighbor query (for one or more points)
- kdtree_k_nearest_neighbors: kNN for a single query point
- kdtree_range_query: rectangular range query
- kdtree_ball_query: queries samples withing distance delta from a point
IMPORTANT NOTE: as Matlab offers a kdtree I have lost interest in maintaining this code.

Comments and Ratings (49)


I fixed it on my mac adding this in the MyHeaps.h file

# define __is_heap is_heap


Can you provide some help for the compilation on recent OSX.
It did not compile on Matlab 2016a on Mac Sierra using the Clang compiler, returning this error message:
Building with 'Xcode Clang++'.
Error using mex
In file included from /Users/GVALMTGG/Github/gcms-matlab/src/testing/kdtree-master/toolbox/kdtree_build.cpp:1:
In file included from /Users/GVALMTGG/Github/gcms-matlab/src/testing/kdtree-master/toolbox/KDTree.h:4:
/Users/GVALMTGG/Github/gcms-matlab/src/testing/kdtree-master/toolbox/MyHeaps.h:154:15: error: no member named
'__is_heap' in namespace 'std'; did you mean 'is_heap'?
return std::__is_heap(heap.begin(), heap.end() );
note: 'is_heap' declared here
is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
1 error generated.

thanks for help

sachin pathak

can any one provide me the sample of input???because i m facing some problem when i am giving input "p=imread('C:\Users\IIT PATNA\Desktop\image\torus3d.png');
p=rgb2gray(p);" .
then this is showing the error that
" ??? Undefined function or method 'kdtree_build' for input arguments of type 'uint8'.

Error in ==> kDensity at 28
tree = kdtree_build(points);"


tep (view profile)

I got system crashes on my windows 64 bit machine, the problem was that pointers were casted to 4-Byte longs with visual studio c++. See here:


tep (view profile)

Hello everybody, I just want to be clear about why I have stopped supporting this library.

I know many have reported my code is much faster than what is natively offered, but I have simply lost faith in mathworks.

I have been told by many this was the de-facto standard kdtree used by many researchers, and the fact that they released their own version without even giving out a simple token of acknowledgement was not very pleasant.

You should go ahead and use what they offer:

Have a great day

please give me sample input for this


vivek (view profile)

Can i use the KD tree to find intersections in N rectangles and compute the overlap area.Any idea will be regrettably appreciated.

Ehsan golk

I found that the data must be double to work properly, if you get "Matlab System Error", cast it.

Ehsan golk

it is working fine with random data and examples but i dont know why it is not working in my data i have 279936x3 data. I even made a t = rand(279936,3); and its working but i dont know why ist not working on my data. i get "Matlab System Error" in kdtree_build(mydata);

Ehsan golk


Kobye (view profile)

Extremely efficient, works great. Rare crashes as previously reported but not at a problematic interval.

Thien Tran

I have same problem mentioned by Jon. I am using R2014a.

Any help, pls


Jon (view profile)

I am experiencing apparently random crashes from the query files in this package. The files compile just fine, but they don't always work.

I randomly get a "Matlab System Error" containing details indicating a segmentation violation on both R2012a and R2013a (Windows 64 bit). My compiler is Visual Studio 10.0

I am employing the kdtree_ball_query within a loop, where every point in the domain is checked. The points in the domain are shifted then checked again. On R2012a, the crash occurs after the same number of point-shifts (making me think it had something to do with the input data), but in R2013a, it crashes immediately.

I have tried the different query functions all with the same result. The kdtree_build function has never caused a crash. I don't know why this is happening, but it's too bad because otherwise this suite of files would be immensely useful!


Hi, thanks for sharing the code.

I found a strange behavior from the computational execution time:


is far way faster than:


being P a point with 25 dimensions.



BESMA (view profile)

I tried to execute this code but i didn't undrestand the steps to do this!! ireally need it any help and thank you.

great work & thx another time Andrea

am posting this for newbies next readers

1) install a compiler (u have to respect the order ) see here :

2) u have to be in matlab on the folder where the files are, see here :


Tarek, that just means you haven't compiled the library. @see kdtree_build

Gracie mille Andrea for answering :)
i tried : mex kdtree_build.cpp

the msg i have is :

mex kdtree_build.ccp

" C:\PROGRA~1\MATLAB~1\R2013A\BIN\MEX.PL: Error: 'kdtree_build.ccp' not found.

Error using mex (line 206)
Unable to complete successfully."

ps : i did set the path


Eran (view profile)

One thing that is very important and missing is a way to save and load the tree to/from disk.
It takes ~1000s to generate a tree for
a 10^6 X 3 matrix. It will be useful if you can do it only once and load it from
hard drive in a fraction of a second.

Lingji Chen

Great work! Thank you!

A question: I inferred this from your demo, but wanted to confirm with you: The index returned by a query is guaranteed to correspond to the row index of the data used to create the kd-tree, correct?

Thank you! Gave my application 100x speedup.


kenza (view profile)

hi every body
it's the first time who i participate in this blog, I am a beginner in matlab programmation. Actually, I try understand the K-d tree code. So i found a matlab sript for the implementing of algorithm. I give you the link to consult the sript code. My question is connected to the input of kdree code especially 'val'. What mean 'val' ? is it a matrix or array and how can i obtain it or calculate it?
I need your help. your answers can give me another reflexion.

Sorry for the butchered english in my last message ^_^

Be advised.. The library has been subject to large updates and it's in Beta. It's much faster and it offers a matlab class wrapper. The updated library can be found at the following URL:
(Includes 64bit binaries for OSX and WIN7)

@Jose, yah the tree is static.. sorry
@Bryan, that's a good question :) I am working on the library these days, I will try to answer it.


Bryan (view profile)

Great work! Performance Question: Why is kdtree_nearest_neighbor() slower than kdtree_k_nearest_neighbors(...,1)? In my testing with the same set of 2000 4-dimensional points, k_nearest is 4x faster.


Jose (view profile)

Great work! I'm using it in my thesis project and it works well. But I don't know how I can delete nodes in the tree meanwhile keep the tree balanced.

Hi Andrea,
Thanks for the file, great work. Just a FYI: the tree doesn't appear to be correctly created in the event there are nan values in the data-set. In my tests, the points need to be at least 50-60% non-nan for the tree to work as expected.

Duy Nguyen

Hello Mr.Andrea Tagliasacchi, your code is really great but i need some other things. I wonder how i can make the function nearest neighborhood get distances between corresponding pairs. I mean that function's output return not only indexes but also the distances. Thank you in advance for your time

Hello Eval, that's a completely different problem, the underlying structure of this kd-tree is built to exploit the complete balancedness of the data. If you need a dynamic kd-tree then you would need to code it differently. By the way, why kd-tree? They are not exactly the best for this kind of task. Have you ever thought about using quad or octrees? Well, unless you have very high dimensional data...

It works really nice, but I need something and I don't know how to do it efficiently. I need to update an existing kd-tree with new data, but without losing the actual indexes. Is that possible? Please could you help me? Thanks in advance for your time....

Very nice and complete work! It worked perfectly. VC Express Ed. 2008 works fine. Thanks a lot!.

The easiest solution would be enclosing the methods in a Matlab class and let Matlab call the "delete" functions automatically.

I might work on it in the future and improve it to include this functionality as well. I suggest you to be more careful with your de-allocations in the meantime :)

This is a really nice implementation. It's worked very well for me and is much faster than other implementations I've tried.

If I accidentally call kdtree_delete twice on the same handle, matlab quits immediately. Would it be possible for the library to maintain an internal list of handles to avoid this problem?

It would also allow implementation of a 'kdtree_delete_all' function, to free up all trees that have been created in a session. That's useful because if a piece of matlab code crashes before it gets to kdtree_delete then you can end up with an orphaned tree.

It would be nice to have a 'kdtree_delete_all' function to free up all trees that have been created. Of course, this would require a list of trees to be maintained within the library.


Ok, Shame on me, there is a method


that needs to be called for releasing the memory again.


On my System (64bit Ubuntu, Matlab R2009a) there seems to be a memory leak with this implementation:

for i = 1:1000
tree = kdtree_build(rand(1000,1));

grabs around 140MB of system memory, according to top. That is never released again. Do I have to release the resources myself in some way or might this be a bug?
I really depend on this implementation, so you would do me a great favour by having a look at it...


Thanks a lot for this contribution - I've been using it a lot recently and it just works perfectly :)

sun jin

D:\kdtree1.2\kdtree\KDTree.h(144) : error C2374: 'dIdx' : redefinition; multiple initialization
D:\kdtree1.2\kdtree\KDTree.h(137) : see declaration of 'dIdx'
D:\kdtree1.2\kdtree\KDTree.h(225) : error C2371: 'i' : redefinition; different basic types
D:\kdtree1.2\kdtree\KDTree.h(223) : see declaration of 'i'

D:\MATLAB\R2008A\BIN\MEX.PL: Error: Compile of 'kdtree_build.cpp' failed.

??? Error using ==> mex at 207
Unable to complete successfully.

lin ming

great work!
note: compile with visual c++ 6.0 will cause fatal error on my computer. However, VS2008 works fine.

Worked perfectly out of the box after compiling in MATLAB as specified by the docs. Thanks a lot!

One little thing: The help for kdtree_k_nearest_neighbors says that the neighbors are returned with increasing distance order. This seems to be incorrect, my experiments tell me they are returned in decreasing distance order (e.g. if the point itself is part of the tree, then it is returned as the last of the neighbors, not as the first).

kdtree_build() returns a pointer to the kdtree. That number needs to be fed as first argument to every other query method. I haven't tried it on older versions of Matlab but I haven't used any of the new releases functionality.

Bing Jian

How to use the result returned by kdtree_build()
which is a double number on my MATLAB7.5.0?
Does your program require at least MATLAB7.6?

Thanks Kigor, I found a simple bug in the kdtree_nearest_neighbor data conversion. The query was executed MxN times instead of M times; given the query matrix Q is of size(M,N).

The updated kdtree_nearest_neighbor.cpp file can be found at

The bug will be corrected in the next release

KIgor Karic

For some reason kdtree_nearest_neighbor takes extremely long time to finish. Are others having the same problem or am I the only one?

The most complete Kd-tree on Matlab exchange.
Thank you Andrea

Gary Tam

Thank you! Work out of the box.



linked to github repo


updated link to git repository (google code dead)


Redirected documentation to my personal page


Updates some interface bugs and the bugs on distances (second argument) returned by the query functions.


Corrected few bugs in parameter passing
Greatly enhanced the preprocessing speed (tree construction) 10x
Improved examples and makefile structure.
More info in "CHANGES"

MATLAB Release
MATLAB 7.6 (R2008a)

Inspired: Kdtree implementation in matlab

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Win prizes and improve your MATLAB skills

Play today