All perfect praise be to Allah, The Lord of the Worlds. I testify that there is none worthy of worship except Allah, and that Muhammad, sallallaahu`alayhi wa sallam, is His slave and Messenger.
In a normal case, masturbation is forbidden. However, in case when one is genuinely in need of it due to the doctor's recommendation and does not find any alternative to it, then, we do not see anything wrong with it in order to ward off harm to the patient if he did not do so.
In this case, the patient must confine himself to what removes the damage only.
Allah knows best.