That does not look like matrix transposition to me, but assuming the output is what is wanted and the rows and columns are the same count then I’d probably just do this horror as a first step (then I’d probably break it up into individual function calls for readability and maintainability):