Matrix elements in harmonic oscillator representations I. General solution and application to one dimension