Calling find(move==0)
will return linear indices of elements in move
which are equal to zero. For example:
move =
1 0 1
0 0 0
0 1 0
>>indices = find(move==0)
indices =
2
3
4
5
8
9
You can take this result and scramble the indices randomly using...
>>scrambled = indices(randperm(length(indices)))
scrambled =
9
2
8
4
3
5
Then choose the first element, scrambled(1)
, as the computer's next choice. There are probably several ways to go about this. The nice thing about this one is that it can be called until the very end of the game to retrieve the computer's next move.
EDIT:
computerMove = indices(randperm(length(indices),1));
This will return the first element automatically as Dennis pointed out.