I have a simple task to transponse a square 2D array: (I need to do it in a very plain manner, no containers etc)
static void Main(string[] args)
{
double[,] a = new double[5, 5];
Random random = new Random();
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
a[i, j] = random.NextDouble();
}
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
Console.Write(a[i, j] + " ");
}
Console.WriteLine();
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
double temp = a[i, j];
a[i, j] = a[j, i];
a[j, i] = temp;
}
}
Console.WriteLine("\n\n\n");
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
Console.Write(a[i, j] + " ");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
I was expecting a reversed array as the output. However, I got the same array here. Please, help me find out what did I do wrong?
The transpose of a matrix is obtained by moving the rows data to the column and columns data to the rows. If we have an array of shape (X, Y) then the transpose of the array will have the shape (Y, X).
The numpy. transpose() function changes the row elements into column elements and the column elements into row elements. The output of this function is a modified array of the original one.
To calculate the transpose of a matrix, simply interchange the rows and columns of the matrix i.e. write the elements of the rows as columns and write the elements of a column as rows.
This happens because you are executing both for
loops from 0
to 5
. So you are doing the transpose twice.
For example, for i=0
and j=1
you transpose a[0,1]
with a[1,0]
and when i=1
and j=0
the values of a[1,0]
and a[0,1]
going back to its original position.
You can make the inner for
from 0
to i
, so the positions are swapped just one time.
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < i; j++)
{
double temp = a[i, j];
a[i, j] = a[j, i];
a[j, i] = temp;
}
}
The third loop swaps both diagonal halves of the array, you have to swap only the elements from one half:
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < i; j++)
{
double temp = a[i, j];
a[i, j] = a[j, i];
a[j, i] = temp;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With