You know, it's quite possible that med schools don't have much of a profit margin. That's because they need real doctors to teach. Med school professors easily make 2-3 times as much as equally qualified and experienced physics/engineering professors. They need to be paid that much because, otherwise, it would be more profitable for them to leave academia.
So we're back to the original question, why is it that doctors are paid better than engineers? Cost of education is a consequence, not a cause. Despite exorbitant costs, people pile into med schools at such a rate that most of those schools have acceptance rates in single percentages (at most one in ten applicants is offered admission in most schools). It's harder to get into the med school at the University of South Alabama than it is to get into MIT. Clearly, there's a bottleneck somewhere that keeps the number of med students low, and, consequently, their potential salaries high.
Imagine if there were a federal regulation that required you to have a government-issued permit in order to write code. Further, imagine that the government issued 10,000 of those every year to graduates of a small number of elite colleges and eligible immigrants. Finally, imagine that it isn't possible to outsource, and every line of code that has to be written, must be written by a licensed U.S. resident. How much would such licensed programmers make? A lot more than today, you can be sure of that.
What's the nature of that bottleneck with regard to doctors? It's called "residency". In most states, all doctors have to work at least one year as hospital residents before they are permitted to practice medicine on their own. The number of available residency positions has been virtually flat, at around 24,000, for the last couple of decades. Medical schools are interested in making sure that all their graduates are employed, therefore they keep the number of students low enough for all of them to find residency spots upon graduation.