Movement is essential for an animal to interact with its environment. Furthermore, the better the animal learns the specific demands of the environment, the more fluent is the motor execution. The study of motor control, and how sensorimotor integration guides motor control, is important for understanding the function of neural networks. It is known that the primary motor areas are organized in a topographical manner, but the knowledge on how environmental demands are reflected and encoded in cortical neuronal activity and how this can be shaped by learning is still limited. In my thesis work I focused on how contextual information is encoded in the mouse motor cortex, using two-photon imaging combined with a regular vs. irregular rung ladder locomotion task and across learning. I found that context-depend activity in the primary motor area M1 develops during learning, especially for highly skilled grasping actions, but breaks apart upon silencing of projections from secondary motor cortex. Furthermore, neuronal populations in secondary motor cortex M2 enable adaptive motor behavior by refining context-specific activity patterns.