MATLAB: Steps between to elements of a matrix

distanceelementsshortest

Given the a matrix A filled with 0,1 and 2. I need the shortest distance from a given element (lets say A(7,8)) to the next element containing a 1 or a 2.
I use [R,C] = find(1); Distance = (abs(R-i) + abs(C-j)); B = [R,C,Distance]; [value, row] = (min(B(:,3)));
to find the shortest distance. This just consider 1 horizontal and 1 vertical move. Now i need the shortest distance considering horizonal, vertical and diagonal movement or an combination of them.
A = [1 1 2 2 0 1 1 1 1 0; 1 0 2 2 0 1 1 1 1 0; 1 1 2 2 1 1 1 1 1 1; 1 1 2 2 1 1 0 1 0 1; 1 1 2 2 0 1 2 2 0 2; 1 1 0 0 1 0 2 2 2 2; 1 1 1 1 1 1 2 2 2 2; 1 0 2 2 0 1 2 2 2 2; 0 2 2 2 0 2 2 2 0 0; 2 2 2 2 2 2 2 0 0 1]

Best Answer

This might help you further:
A = [1 1 2 2 0 1 1 1 1 0; 1 0 2 2 0 1 1 1 1 0; 1 1 2 2 1 1 1 1 1 1; 1 1 2 2 1 1 0 1 0 1; 1 1 2 2 0 1 2 2 0 2; 1 1 0 0 1 0 2 2 2 2; 1 1 1 1 1 1 2 2 2 2; 1 0 2 2 0 1 2 2 2 2; 0 2 2 2 0 2 2 2 0 0; 2 2 2 2 2 2 2 0 0 1] ;
LocRC = [7,8]
[r,c] = ndgrid(1:size(A,2),1:size(A,1))
Distances = zeros(size(A)) ;
Distances(:) = hypot(r-LocRC(1), c-LocRC(2)) ;
tf = A==1 | A==2
Distances(~tf) = Inf ;
[MinDistance, MinIndex] = min(Distances(:))
[MinR, MinC] = ind2sub(size(A),MinIndex)