finding nearest vlaue
Show older comments
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
Accepted Answer
More Answers (1)
Andrei Bobrov
on 6 Apr 2012
A=[1 2 8
7 9 6
10 14 89]
a = zeros(3);
out = cell(numel(A),2);
for i1 = 1: numel(A)
b = a;
b(i1) = 1;
out(i1,:) = {A(i1),A(bwdist(b,'chessboard') == 1)};
end
OR
B = nan(size(A)+2);
B(2:end-1,2:end-1) = A;
m1 = bsxfun(@plus,(1:3).',(0:2)*size(B,1));
i1 = bsxfun(@plus,m1(:),m1(:).'-1);
B1 = B(i1);
ic = ceil(size(i1,1)/2);
out = [B1(ic,:)' sort(B1([1:ic-1,ic+1:end],:).',2)];
With show?
B = nan(size(A)+2);
B(2:end-1,2:end-1) = A;
m1 = bsxfun(@plus,(1:3).',(0:2)*size(B,1));
i1 = bsxfun(@plus,m1(:),m1(:).'-1);
B1 = B(i1);
ic = ceil(size(i1,1)/2);
B2 = arrayfun(@(ii)reshape(B1(:,ii),size(A,1),[]),(1:size(B1,2))','un',0);
t2 = cellfun(@(x)~isnan(x),B2,'un',0);
out = [num2cell(B1(:,ic)),cellfun(@(x,y)x(any(y,2),any(y)),B2,t2,'un',0)]
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!