How to transpose matrices in programming – Unity C# Implementation

Introduction

In previous entries we saw how to define matrices in programming and load data into them, in this article we will see an algorithm to transpose a matrix in programming, using C# language in Unity.

Initial data

We will start from an “A” matrix with preloaded data and we will analyze a method that will perform the transposition of the matrix sent as parameter and will return the result matrix.

Fig. 1: Declaration of a matrix “A” and call to a function that returns its transposed matrix.

Algorithm for transposing matrix of N rows and M columns

Transpose a matrix implies transforming its rows into columns and its columns into rows, therefore the resulting matrix will be a matrix that will have its dimensions exchanged. The function that will be in charge of transposing the matrix that enters as parameter is shown in figure 2, first we will read the number of rows and columns of the input matrix and we will create the structure of the result matrix, this is done in lines 30, 31 and 32 respectively, notice how in the creation of the result matrix, the dimension is exchanged comparing with the input matrix.

Then we have to traverse each element of the input matrix, we have seen that this could be done by two nested for-loops, the first one traverses rows and the inner loop traverses columns. Inside the loop what we will do is to assign the ij-element of the input matrix, to the ji-element of the output matrix.

At the end of the loop, the result matrix is returned (line 41).

Fig. 2: Algorithm for transposing a matrix.

Exit mobile version
Secured By miniOrange