MATLAB: Finding nearest vlaue

nearestvalue

I have an matrix
A=[1 2 8
7 9 6
10 14 89]
now i want to find the nearest value for example,lets ur assume 2,the nearest values are 1,7,9,8,6
for 1 it is 2,7,9
please tell how to find the nearest value

Best Answer

Kash,
You might want to try this. It'll allow for you to do the neighbors of more than 1 number at a time. Just change the variable val to be what you want (either a scalar, or a vector).
A = [1 2 8
7 9 6
10 14 89];
val = [1 2];
[y x] = find(ismember(A,val));
ys = unique(bsxfun(@plus,y,-1:1));
xs = unique(bsxfun(@plus,x,-1:1));
ys(ys <= 0 | ys > size(A,1)) = [];
xs(xs <= 0 | xs > size(A,1)) = [];
A(ys,xs)