This problem has occured for many of my patients in the past. It is more common in men. I suggest you see a doctor for further tests, such as an mri to ensure nothing else is wrong. This problem can occur because of multiple situation. First, what poistion are you masturbating in? Often times ackward positions can cause muscle spasm that can disrupt the nerves and cause massive headaches. Are you on any other medications that affect hormones? E.G. Viagra? How is you blood pressure?
How you masturbate or have sex can have a lot to do with this problem as well. I suggest you see a doctor because other questions I would ask would be a little more personal and could uncomfortable online. See a doctor as soon as possible.