I know it's counterintuitive, but Spain and Portugal don't combine well, because there are very limited transportation options between them. There are no fast trains and driving can take hours and hours, plus if you don't drive a loop returning to the first country, you are dinged with a very hefty drop-off fee. Most people fly between the two countries. I haven't been to Portugal yet, but I've been in Spain 3 times in the last 5 years and there is plenty to fill up 15-18 days in and around Madrid and in Andalusia.
Spanish trains are the best way to get around with one exception, that I'll get to in a moment. Renfe is the name of the train system and it's very good but there are a lot of choices and their website is not the most user-friendly. It's best to read this article first and then refer to it when you use the website.
My ideal itinerary would be Madrid, Toledo, Cordoba, Sevilla, the pueblos blancos (white hill towns) and Granada. It may be best to fly round trip Madrid (AFAIK it's the only airport, other than Barcelona, that has direct flights to the US), depending on where you live. If you decide to include Portugal, then fly open-jaw Madrid/Lisbon.
If you include the pueblos blancos in your trip, that's the place a car will be useful. Use it between Sevilla or Cordoba and Granada.