Clear Filters
Clear Filters

Steps between to elements of a matrix

2 views (last 30 days)
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]

Accepted Answer

Jos (10584)
Jos (10584) on 14 Apr 2016
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)

More Answers (1)

Guillaume
Guillaume on 14 Apr 2016
It sounds like you are trying to compute:
bwdist(A, 'chessboard')
Note that this requires the image processing toolbox.

Categories

Find more on Robust Control Toolbox 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!