Your original itinerary sounds great, but here's a few other options.
From Lisbon, it's easier to get to Seville than Malaga. Loads to do in Seville! It's also easier to get to Madrid from here.
If you do Málaga, take a day trip to Ronda and also a day trip to do the Caminito del Rey - perfect for hiking and a little bit of adventure. Not as scary as they make out either.
Consider Granada too - the Alhambra is fantastic, and you could even do a day trip to the Sierra Nevada.
You could easily do an Andalusia trip, and would still find the weather very pleasant in October.
Potential itinerary
Malaga - 3nts (1day Malaga city, 1 day Ronda, 1 day Caminito del Rey)
Seville - 3nts
Cordoba - 1nt
Granada - 2nts
Nerja - 4nts (beach, relax, day trips to Frigliana and the caves)
Madrid / Barcelona- rest of the stay take the bus back to Malaga or Granada and catch the high speed train to Madrid or BCN from there.
You could do this route in other ways depending on flights
Seville - Cordoba- Granada - Nerja - Malaga
Seville - Cordoba-Malaga -Nerja- Granada
Accomodation is generally quite cheap in this area, particularly Seville, Granada and Cordoba in the summer months as most people escape to the coast. It would be hot, but head out in a morning, chill in the afternoon and explore again in the evening. October is good value too, and the weather is often still mid twenties.