Mexico went ahead in the 10th minute when Brazil defender David Luiz put the ball into his own net, and the hosts' chances were boosted further when Dani Alves gave away a penalty and was sent off in the process for a foul on Javier Hernandez late in the first half.
However Andres Guardado failed to convert the penalty.
Ronaldinho equalized for Brazil with a trademark freekick into the top right corner of the net in the 80th minute, and Marcelo scored the winner four minutes later.
The defeat was the first for Mexico coach Jose Manuel de la Torre in 15 games in charge of the national team.
In a fast paced game, the opening goal came when Pablo Barrera broke free down the right and put in a low cross, which Luiz tried to clear but only deflected the ball into the net.
Neymar broke free inside the penalty area for Brazil in the 17th but shot over the bar with only goalkeeper Oswaldo Sanchez to beat.
Barcelona fullback Alves received a second yellow card for shoving Manchester United striker Hernandez to the ground inside the penalty box as the ball was sailing harmlessly through to the goalkeeper.
Keeper Jefferson saved low to his right from Guardado*s resulting penalty.
Hernandez had Mexico's best chance of the second half but his close-range header was saved by Jefferson.
Ronaldinho scored from 20 yards in the 80th and the winner was scored when Marcelo drove into the penalty area and hit a fierce shot past Sanchez, who won his 100th cap in the game.
The game took place with a heavy security presence in the northern city of Torreon after recent violence, including the suspension of a Mexican first division game on Aug. 20 due to a gunfight close to the stadium.
For Brazil, the match was the latest in a series of friendly games, as it automatically qualifies for the 2014 World Cup as host and therefore is not participating in the current South American qualifiers.