Matsuyama, who held a share of the halfway lead, lost ground on Saturday with a level-par 71 but he bounced back in style to close with a bogey-free 65 to medal in his second Olympics.
Earlier in the day, Rahm seemed on track to win gold for Spain as he opened up a four-shot lead around the turn but back-to-back bogeys at the 11th and 12th thwarted his momentum. A double-bogey seven at the 14th further hurt his hopes before he missed out on the podium altogether with back-to-back bogeys on his final two holes.
His Ryder Cup teammate McIlroy finished alongside him after a spirited closing 66, with a double bogey at the 15th when he found water with his approach ultimately ending his chance of a medal.