166 views (last 30 days)

Show older comments

Matt J
on 11 Sep 2013

Edited: Matt J
on 11 Sep 2013

What I often like to do is make an offset mask, as follows

s=size(yourmatrix);

N=length(s);

[c1{1:N}]=ndgrid(1:3);

c2(1:N)={2};

offsets=sub2ind(s,c1{:}) - sub2ind(s,c2{:})

Now, for any linear index in your matrix L, you can get all its neighbors by doing

neighbors = yourmatrix(L+offsets)

It won't work at the edges of the matrix, but you can take care of that by padding the edges first.

Image Analyst
on 31 Oct 2017

Shashank Prasanna
on 11 Sep 2013

If you have the Statistics Toolbox installed, there are couple of nearest neighbor searching tools that you might find very useful. Although some of these concepts may be advanced for a casual user, the functionality itself is very quite easy to use, that's really the power of MATLAB:

One way to speed up higher dimensional neighbor searching is to use an optimized data structure such as k dimensional trees, and this is easy to do so as below:

kdtreeNS = KDTreeSearcher(x);

[n,d]=knnsearch(kdtreeNS,x);

Here is the page from the doc:

Shashank Prasanna
on 11 Sep 2013

Michael, I misunderstood your question. I made the assumption that you were referring to the columns as dimensions in |R^n space .

None of these function work on multidimensional matrices. If you have data in some n dimensional space each instance or observation can be represented as a vector with n entries. I am not sure how your data is represented but if you are able to represent it in a why described you can use all the functionality that I mentioned to do your neighbor search.

Image Analyst
on 11 Sep 2013

Image Analyst
on 11 Sep 2013

I'd use loops over each dimension, so for 5 dimensions like my example

for d1=1:d1max

for d2=1:d2max

for d3=1:d3max

for d4=1:d4max

for d5=1:d5max

subHyperVolume = hyperVolume(...

d1-1:d1+1,...

d2-1:d2+1,...

d3-1:d3+1,...

d4-1:d4+1,...

d5-1:d5+1,...

);

end

end

end

end

end

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

Start Hunting!