Ducati's reigning seven-time world champion took the chequered flag in a dramatic 13-lap sprint to go four points clear of his fellow Spaniard in the standings.
Martin, who had led the race on his Aprilia at the halfway point, finished fourth in blistering hot and dry conditions at the Mandalika International Circuit.
Japan's Ai Ogura and Italy's Fabio Di Giannantonio were second and third.
There was mayhem at the start as Spain's debutant pole-sitter Raul Fernandez and Marco Bezzecchi collided and crashed out on the first corner.
Martin took full advantage to seize the lead, with championship rival Marquez second, both having started from the second row.
With his compatriot breathing down his neck, Martin held his nerve to streak 1.5 seconds ahead at the halfway stage.
But the former world champion, having been cruising, then abruptly slowed up and surrendered the lead to Marquez, possibly because of tyre pressure issues.
That gifted the lead to Marquez, who romped home for his first win in Indonesia.
The Grand Prix is on Sunday.
There are just five race weekends after this, starting in Australia in a fortnight.
