Hello, I can understand the distress you are through. I can suspect few conditions. It can ve a psychological ED. You may be able to have good erections while masturbation, however while intercourse you may face difficulties. I would need to explore any fault with the masturbation technique here. Masturbation per say may not be harmful. But an improper masturbating techniques can cause such an issue. Use of pornography while masturbating is an important risk factor. Anxiety issue must also be explored in detail. I would suggest you to consult with a sexologist.
Next Steps
For more information and specific advices on management you can consult with me directly here on practo.