0

I am trying to transpose a int[,] matrix. But I do not get the correct output. I have done the transposition with two for-loops but I think I did a mistake there. I just can't point it out.

Here is my code:

int[,] matrix = new int[2,2];
matrix[0, 0] = 1;
matrix[0, 1] = 2;
matrix[1, 0] = 3;
matrix[1, 1] = 4;

public void transponieren()
{
    int[,] temp = this.matrix;

    for (int i = 0; i < this.matrix.GetLength(0); i++)
    {
        for (int j = 0; j < this.matrix.GetLength(1); j++)
        {
             this.matrix[i, j] = temp[j, i];
        }
    }

    transponiert = true;
}

With an input of

[ 1 , 2 ]
[ 3 , 4 ]

I get an output of

[ 1 , 3 ]
[ 3 , 4 ]

I have already another solution that works but I want to know what I did wrong here as I only copied the working solution from somewhere else.

4

4 回答 4

3

Your problem is that this line:

int[,] temp = this.matrix;

does not make a new array. Because int[,] is a reference type, you end up with temp referencing this.matrix, so any changes to one of those matrices will affect the other.

Your logic requires that temp is actually a separate array, so it fails.

So you just need a new array of the correct size:

var temp = new int[this.matrix.GetLength(0),this.matrix.GetLength(1)];

However, note that making a temp array like that to transpose a square matrix is very inefficient, since you can do an in-place transpose (but only if you don't mind destroying the original contents).


[EDIT] Extra sample: How to in-place transpose a square matrix.

public void TransposeSquareMatrixInPlace(int[,] matrix)
{
    if (matrix == null) throw new ArgumentNullException("matrix");
    if (matrix.GetLength(0) != matrix.GetLength(1)) throw new ArgumentOutOfRangeException("matrix", "matrix is not square");

    int size = matrix.GetLength(0);

    for (int n = 0; n < (size-1); ++n)
    {
        for (int m = n+1; m < size; ++m)
        {
            int temp = matrix[n, m];
            matrix[n, m] = matrix[m, n];
            matrix[m, n] = temp;
        }
    }
}
于 2013-06-07T09:50:47.043 回答
1
int[,] temp = new int[this.matrix.GetLength(0),this.matrix.GetLength(1)];

for (int i = 0; i < this.matrix.GetLength(0); i++)
{
    for (int j = 0; j < this.matrix.GetLength(1); j++)
    {
         temp[i, j] = this.matrix[i, j];
    }
}
this.matrix = temp

transponiert = true;
于 2013-06-07T09:47:12.970 回答
1

int[,] temp = this.matrix;

temp variable is holding a reference to the matrix variable. Hence, when i=0, input matrix is getting modified.

于 2013-06-07T09:51:01.047 回答
1
public void Transposition(){
    MatRes = new int[Mat1.GetLength(1), Mat1.GetLength(0)];
    for (int i = 0; i < Mat1.GetLength(1); i++){
        for (int j = 0; j < Mat1.GetLength(0); j++){
             MatRes[i, j] = Mat1[j, i];
        }
    }
}

Works for every kind of matrix, considering Mat1 as the matrix to transpose and MatRes the transposed matrix.

于 2016-02-27T16:04:39.927 回答