Steps between to elements of a matrix

2 次查看(过去 30 天)
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]

采纳的回答

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

更多回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 Robust Control Toolbox 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by