Trains in Morocco are OK, and reliable!
But you'll have to pay a supplement for each train, because every train is now declared as a train rapide.
Look for the timetable on rail.shop/oncf
because there are only a few trains running every day.
From Melilla you take the Bus to Oujda or walk over the border and take the bus or the shared taxi to Nador and from there to Taourit.
From Oujda or Taourit the train ride to Marrakesh is about 13 hours (eventually change at Sidi Kacem, Rabat or Casablanca), so it's quite a long way.
It's much faster to take the ferry from Algeciras (Spain) to Tanger (Morocco). From there you don't need to take a bus or shared taxi (just a really cheap taxi to the station if you like) and it's about 9 hours to Marrakesh by train (eventually change at Sidi Kacem).
I hope I could help you!