The pair stretched one another to the limit in a superb seventh game, which saw a 34-shot rally and fine winners by both players, before Ferrer edged it to go 5-2 up, only to then lose three games in a row.
Murray saved one set-point with a fine double-handed forehand winner before Ferrer won the set.
The second set began in equally close fashion, and after another hard-fought break of serve to go 2-0 up, Ferrer won the next game ominously quickly to suggest the match was slipping away from Murray.
Murray replied strongly, holding serve, breaking back and then winning a drawn-out sixth game to go level at 3-3.
It was definitely the best standard of match I've played on clay so far this year
However, despite Murray's valiant battling, his dogged opponent showed great concentration and fitness, and the patience of the home crowd was rewarded when Murray put a return in the net and Ferrer won after two hours 15 minutes.
World number four Murray had lost five of his 10 matches since reaching the Australian Open final at the start of the year but victories over Juan Ignacio Chela and Victor Hanescu in Madrid suggested he is coming back into form.
"It's been very good. The first two matches were obviously great to win, sometimes you lose matches where you play well," said Murray.
"Tonight's match was not one I was necessarily expected to win, but over two hours for a 7-5 6-3 match kind of suggests that it was very close.
"There were a lot of rallies, I had my chances, he had his. He's played a lot of matches on the clay this year so maybe it's normal that he might have played a bit better, but it's been a positive week.
"I'm obviously very disappointed to lose, I would've liked to have got to the semis here but it was not to be.
"I thought I played a very good match, got a bit unlucky at certain points, but it was definitely the best standard of match I've played on clay so far (this year)."
This page is best viewed in an up-to-date web browser with style sheets (CSS) enabled. While you will be able to view the content of this page in your current browser, you will not be able to get the full visual experience. Please consider upgrading your browser software or enabling style sheets (CSS) if you are able to do so.