So you have an array of structs, and move around the structs inside the array? That seems extremely inefficient to me.
Also, the reason the borderMatrix
-line takes so long is because you are constructing a possibly large array.
Here's a suggestion for handling moving creatures:
Store your creatures as a nCreatures-by-mProperties numeric array. It's much easier to apply functions on a column of an array that to crawl individual fields. For example creatures = [x,y,prop1,prop2];
Move your creatures one-by-one:
for iCreature = 1:nCreatures
currentPos = creatures(iCreature,1:2);
%# initialize array of allowed moves with border conditions
goodMoves = [currentPos(1) > 1, currentPos(2) > 1, currentPos(1) < maxX, currentPos(2) < maxY, true];
%# check for neighbors
if any(creatures(:,1) == currentPos(1) - 1 & creatures(:,2) == currentPos(2))
goodMoves(1) = false;
end
%# etc
%# identify remaining good moves
if any(goodMoves(1:4))
goodMoveIdx = find(goodMoves);
move = goodMoveIdx(randi(length(goodMoveIdx)));
else
move = 5; %# remain stationary
end
end