My impression was that men get erections at night to prevent themselves from peeing when they have a full bladder while asleep.
But Wikipedia suggests that there is some controversy around the exact causes. https://en.wikipedia.org/wiki/Nocturnal_penile_tumescence
It’s hard to imagine what reason a sleeping octopus would have for cycling through colors if not related to their dreams.