Enea Bastianini sees off championship leader to claim sprint victory at Thai Grand Prix
Martin's second place allowed him to narrowly increase his lead over pole-sitter Bagnaia in the championship by two points to 22 heading into Sunday's race.
Martin nearly had a dream start when he rocketed into the lead for a split second going into the first turn, but his aggression cost him as he drifted wide and fell to fifth, while Bastianini moved up to the front ahead of teammate Bagnaia.
"Believe me, I think it was the most difficult race of the season, it was so hot behind the other riders," Martin said.
"On the first lap I was braking very hard and I saw that if I released the brake I would hit someone, so I preferred to go wide and lose some positions and then from that moment on I just pushed very, very hard, recovered positions and achieved the objective today.
"Tomorrow will be a long day, very different, and I hope we can do the same."
Martin gradually moved back up to fourth and overtook Gresini Racing rider Marc Marquez to move in behind Bagnaia.
With Martin hot on his heels, Bagnaia did his best to hold on but he was eventually chased down in the seventh lap, though his Pramac Racing rival risked incurring a long-lap penalty after coming within centimetres of exceeding track limits.
"I started well but then I lost the positions. I was missing something, which is quite strange compared to my feeling in the other sessions," Bagnaia said.
"But in any case we managed to finish third, we lost two points and we can be focused for tomorrow."
Neither of the two title rivals ever looked close to denying Bastianini the victory as the Italian built up a comfortable lead and crossed the line well ahead of Martin.
Marquez and his brother Alex (Gresini) finished fourth and fifth, while Pramac Racing's Franco Morbidelli was sixth. VR46 Racing duo Marco Bezzecchi and Fabio Di Giannantonio completed a top-eight lockout for Ducati.
The penultimate race of the season takes place in Malaysia next weekend, with the season coming to a close in Valencia two weeks later.