In the minutes leading up to the incident, defendant, Adam Peacock, told the Sheffield doctor he had been having thoughts of exposing himself in public, Sheffield Crown Court heard.
"He said he had done it a few years ago, but no-one had pressed charges," said Richard Thyne, prosecuting.
The court was told how the doctor left the treatment room to get advice, and when she returned Peacock said words to the effect of: 'I find it difficult to be around young, attractive females without exposing myself'.
Peacock then stood up, exposed himself and began performing a solo sex act. He cornered the doctor, who cannot be named for legal reasons, and started sexually assaulting her.
Mr Thyne said the woman tried to break free to reach for the panic button but was stopped from doing so by Peacock.
She eventually managed to escape his grasp, but he cornered her again and continued with the sexual assault.
The terrifying incident only came to an end when other staff members came in to the treatment room and intervened, after hearing her screaming.
In a victim impact statement, the woman said that while the incident probably lasted around two minutes, it felt like it had 'lasted a lifetime'.
"She describes how she previously felt safe at work, but now feels unsafe," added Mr Thyne.
Peacock, of Bradfield Way, Waverley, Sheffield, was arrested at the scene and was initially remanded into custody, before being transferred to a mental health facility.
He pleaded guilty to one count of sexual assault at an earlier hearing.
The court was told how Peacock had received a diagnosis of autism at the end of last year, and medics from the early intervention team treating him shortly before this offence took place had given him a provisional diagnosis of paranoid schizophrenia
Defence witness, Consultant Forensic Psychiatrist, Srikanth Nimmagadda, told the court he agreed with the diagnosis of paranoid schizophrenia, adding that Peacock was now taking appropriate medication but had groped a female member of staff treating him as recently as last week.
Dr Nimmagadda said the fact Peacock had only developed the condition relatively recently meant that the chances of being able to treat him were good, and recommended he be punished by way of a Section 37 hospital order that would see Peacock kept in a medical facility until he no longer poses a risk to the public.
Judge Roger Thomas QC sentenced Peacock to a Section 37 hospital order.
He said: "What you did was very disturbing, and unhappily, she will have to carry this experience with her thereafter."
The Sheffield Rape Crisis Centre offer confidential helpline support as well as counselling and advice on giving support to others who have been raped or sexually abused.
Call their confidential helpline on 0808 802 9999, which is open every day between 10am and midnight, or visit their website here.