It is unknown how dendritic nonlinearities and plasticity mechanisms contribute to computations at the level of neural circuits. We developed a theory that formalises how dendritic nonlinearities that are optimal for integrating synaptic inputs depend on the statistics of presynaptic activity patterns. Our theory accurately predicts the responses of two types of cortical pyramidal cell to patterned two-photon glutamate uncaging. We also derived optimal rules for structural and intrinsic plasticity which ensure that neurons stay tuned to the statistics of their inputs. The optimal structural plasticity rule efficiently identifies ensembles by clustering synapses along the dendritic tree. The same principle suggests an intrinsic plasticity rule for fine-tuning the nonlinear properties of dendritic branches to the dynamics of their presynaptic ensembles, reproducing experimentally observed forms of branch-strength potentiation. These results reveal a new computational principle underlying dendritic integration and plasticity by suggesting a tight functional link between cellular and systems-level properties of cortical circuits.