Your problem is known as Erectile Dysfunction. It has psychological and physical reasons behind it. With younger age, psychological reasons are more likely. If you are getting proper erection and able to maintain it during masturbation then it is more of psychological problem. It is very difficult to find out the underlying cause/causes unless I know the details of your sexual life. You are required to discuss your sex life in detail, past experiences and many other details. If you want to see Doctor personally then consult Psychiatrist. They deal with sex related problems.