Skip to content

Commit

Permalink
squareNeighbors returns neighbors of arbitrary order
Browse files Browse the repository at this point in the history
  • Loading branch information
ralfHielscher committed Mar 21, 2024
1 parent 5d7ccfb commit 8021817
Showing 1 changed file with 27 additions and 8 deletions.
35 changes: 27 additions & 8 deletions geometry/geometry_tools/squareNeighbors.m
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
function ind = squareNeighbors(RowsCols,Nid)
function ind = squareNeighbors(RowsCols,Nid,varargin)
% return the neighbor ids in a square grid
%
%

[col,row] = meshgrid(1:RowsCols(2),1:RowsCols(1));

dRow = [0 1 0 -1];
dCol = [1 0 -1 0];
order = get_option(varargin,'order',0);
if order == 0
dRow = [0 1 0 -1];
dCol = [1 0 -1 0];
else
[dRow,dCol] = meshgrid(-order:order);
dRow(2*order^2+2*order+1) = [];
dCol(2*order^2+2*order+1) = [];
end

if nargin == 2
if nargin >= 2 && ~isempty(Nid)
ind = calcInd(Nid);
else

Expand All @@ -18,17 +25,29 @@
end

end

function indLocal = calcInd(Nid)

nrow = row + dRow(Nid);
ncol = col + dCol(Nid);

% ensure coordinates are within the range
ncol = max(min(ncol,RowsCols(2)),1);
nrow = max(min(nrow,RowsCols(1)),1);
if check_option(varargin,'strict')

indLocal = zeros(size(nrow));
isInside = ~(ncol<1 | ncol>RowsCols(2) | nrow<1 | nrow>RowsCols(1));

indLocal(isInside) = sub2ind(RowsCols,nrow(isInside),ncol(isInside));

indLocal = sub2ind(RowsCols,nrow,ncol);
else
ncol = max(min(ncol,RowsCols(2)),1);
nrow = max(min(nrow,RowsCols(1)),1);

indLocal = sub2ind(RowsCols,nrow,ncol);
end




end

Expand Down

0 comments on commit 8021817

Please sign in to comment.