closest index in matrix between two values
4 views (last 30 days)
Show older comments
hello, i have 2d matrix for example:
X = [0 0 0 0 0;
1 1 1 1 1;
0 1 2 1 0;
1 1 1 1 1;
0 0 0 0 0]
i want to get closest index of columns and rows between value 2 and 0. Is there any chance to do this??
Regards
2 Comments
Accepted Answer
Stephen23
on 8 Jul 2016
Edited: Stephen23
on 8 Jul 2016
X = [0 0 0 0 0;
1 1 1 1 1;
0 1 2 1 0;
1 1 1 1 1;
0 0 0 0 0];
[R0,C0] = find(X==0);
[R2,C2] = find(X==2);
Rm = bsxfun(@minus,R0,R2.');
Cm = bsxfun(@minus,C0,C2.');
% Xd = abs(Rm) + abs(Cm);
Xd = sqrt(Rm.^2 + Cm.^2); % this could probably be improved.
[R,~] = find(Xd==min(Xd(:))); % and a tolerance might be useful here...
and the indices of the zeros closest to the two are:
>> [R0(R),C0(R)]
ans =
3 1
1 3
5 3
3 5
More Answers (2)
José-Luis
on 8 Jul 2016
X = [0 0 0 0 0;
1 1 1 1 1;
0 1 2 1 0;
1 1 1 1 1;
0 0 0 0 0];
[tx,ty] = find(X==2);
x_dist = abs(tx-(1:size(X,1)));
y_dist = abs(ty-(1:size(X,2)))';
dist_array = bsxfun(@plus,x_dist.^2,y_dist.^2);
[ix,iy] = find(dist_array == min(dist_array(X==0)))
0 Comments
Andrei Bobrov
on 8 Jul 2016
z = bwdist(X == 2).*(X == 0);
[ii,jj] = find(z == min(z(z~=0)));
2 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!