I have a big square matrix of structs which represents creatures. Each creature can move left,up,right or down. I'm checking the neighbouring matrix positions for empty cells and do the following calculation for the new coordinates:
function res = Move2(worldDimension,row,col,left,up,right,down)
%In the following matrices, good moves are > 0.
%Directions pattern:
patternMatrix = [0 2 0;
1 5 3;
0 4 0];
%Possible border moves:
borderMatrix = [0 (row>1) 0;
(col>1) 1 (col<worldDimension);
0 (row<worldDimension) 0;];
%Possible neighbor moves:
neighborsMatrix = [0 (up==0) 0 ;
(left==0) 1 (right==0);
0 (down==0) 0;];
%Matrix of possible directions including neighbors and borders
possibleMovesMatrix = ((borderMatrix).*(neighborsMatrix)).*(patternMatrix);
%Vector of possible directions:
possibleMovesVector = sort(possibleMovesMatrix(possibleMovesMatrix(:) > 0));
%Random direction:
randomDirection = possibleMovesVector(randi(length(possibleMovesVector)));
directionCoordsVector = [[row (col-1)];[(row-1) col];[row (col+1)];[(row+1) col];[row col]];
res = [directionCoordsVector(randomDirection,1) directionCoordsVector(randomDirection,2)];
end
This function is kind of slow, when I run the profiler it tells me that:
borderMatrix = [0 (row>1) 0;
(col>1) 1 (col<worldDimension);
0 (row<worldDimension) 0;];
takes 36% of time and that: randomDirection = possibleMove... takes 15% of time. Is there a way I can accelerate the process?
Maybe I can take a different approach by taking from the main game board the free spots arround the coordinate of the creature immediately? If so, how do I take a submatrix if a creature is near the border of the board with out having to deal with off-boundary indexes?
Thanks, Guy.