MATLAB: Closest index in matrix between two values

2d matrixclosestcoordinatefunctionMATLABpoint

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

Best Answer

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