The costs and benefits of group membership vary with the size of groups, and individuals are expected to modify their choice of groups in response to ecological factors such as food availability and predation risk. We experimentally examined context-dependent group size choice in a shoaling fish, the banded killifish, Fundulus diaphanus, by using nondirectional odour cues to simulate a food source or a successful attack by a predator (food or alarm treatments) in the laboratory. Group sizes were significantly smaller in the food treatment and larger in the alarm treatment than in control trials. When presented with food and alarm cues together, fish formed groups that were larger than control groups but smaller than those seen with alarm cues alone. These results are consistent with theoretical predictions based on the known benefits and costs of grouping and with previous laboratory work examining the individual shoal choice behaviour of single fish. To examine possible mechanisms of group formation, we developed an individual-based model of shoaling behaviour in which simulated fish were allowed to modify the area over which they interacted with neighbouring individuals. Group size distributions produced by the model were a good approximation of our experimental data. We suggest that local behavioural interaction rules of this type are a potential mechanism by which fish may individually adjust grouping behaviour without requiring extensive information on the position and movement of all possible shoalmates.