Neuronal networks of the mammalian motor cortex (M1) are important for dexterous control of limb joints. Yet it remains unclear how encoding of joint movement in M1 depends on varying environmental contexts. Using calcium imaging we measured neuronal activity in layer 2/3 of the M1 forelimb region while mice grasped regularly or irregularly spaced ladder rungs during locomotion. We found that population coding of forelimb joint movements is sparse and varies according to the flexibility demanded from individual joints in the regular and irregular context, even for equivalent grasping actions across conditions. This context-dependence of M1 encoding emerged during task learning, fostering higher precision of grasping actions, but broke apart upon silencing of projections from secondary motor cortex (M2). These findings suggest that M1 exploits information from M2 to adapt encoding of joint movements to the flexibility demands of distinct familiar contexts, thereby increasing the accuracy of motor output.