finding nearest vlaue
5 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Jonathan Sullivan
2012-4-6
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)
0 个评论
更多回答(1 个)
Andrei Bobrov
2012-4-6
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)]
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!