From the beginning Madrid was a crazy city. How about a city placed away from the sea, without a major river or harbor? Neither Paris nor London nor Rome nor New York nor Tokyo nor Vienna… The other cities of the world aren’t located in the middle of anywhere.
During centuries, Madrid was just a village founded by the Muslims. Yes, in those Middle Ages times, when Spain was split between two main areas of influence: Christian kingdoms in the North and Muslim territories in the South, the important town in the center of the Iberian Peninsula was Toledo, and Madrid was used as a little fortification to guard Toledo of a possible Christian invasion. You can still see the ruins of the Muslim wall near the current Royal Palace (the biggest Royal palace in the world… but uninhabited, as a part of our peculiarities).