Steps between to elements of a matrix

2 ビュー (過去 30 日間)
Jan Borkovec
Jan Borkovec 2016 年 4 月 14 日
回答済み: Jos (10584) 2016 年 4 月 14 日
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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by