C# Transpose a 2D matrix, looking for the best way

Markus Freitag 3,786 Reputation points
2022-02-15T17:04:27.807+00:00

Hello,
What is the best and easiest way to transform a matrix?
With C# .NET4.8

// The best is with a sample i.e. --> Transpose the matrix from 3,5 to 5,3  
  
namespace WindowsFormsAppMatrixBasic.Core  
{  
    public static class ArrayExtensions  
    {  
        public static T[][] Transpose<T>(this T[][] source)  
        {  
            if (source.Length == 0 || source[0].Length == 0)  
            {  
                return Array.Empty<T[]>();  
            }  
  
            int rows = source.Length;  
            int cols = source[0].Length; // ???  
  
            T[][] result = new T[cols][];  
  
            for (int i = 0; i < cols; i++)  
            {  
                result[i] = new T[rows];  
  
                for (int j = 0; j < rows; j++)  
                {  
                    result[i][j] = source[j][i];  
                }  
            }  
            return result;  
        }  
    }  
  
  
    public class MatrixTest  
    {  
        public void TestMatrix()  
        {  
            List<string> data = new List<string> {  
    "0000",  
    "0000",  
    "0000",  
    "FFFF",  
    "0000",  
    "0000",  
    "0000",  
    "0000",  
    "0000",  
    "0000",  
    "0000",  
    "0000",  
    "FFFF",  
    "0000",  
    "0000"  
};  
  
// ****** From a list, I should make a matrix depend of x and y values.  
// Row	Col	x	y	State	Counter	Coding  
// 1	1	1	10	10	1	32321	0000  
// 2	2	1	20	10	1	32322	0000  
// 3	3	1	30	10	1	32323	0000  
// 4	4	1	40	10	0	32324	FFFF  
// 5	5	1	50	10	1	32325	0000  
  
// 6	1	2	10	110	1	32326	0000  
// 7	2	2	20	110	1	32327	0000  
// 8	3	2	30	110	1	32328	0000  
// 9	4	2	40	110	1	32329	0000  
// 10	5	2	50	110	1	32330	0000  
  
// 11	1	3	10	210	1	32331	0000  
// 12	2	3	20	210	1	32332	0000  
// 13	3	3	30	210	0	32333	FFFF  
// 14	4	3	40	210	1	32334	0000  
// 15	5	3	50	210	1	32335	0000  
  
  
            string[,] matrix = new string[,]  
{  
    {"0000", "0000", "0000", "FFFF", "0000"},  
    {"0000", "0000", "0000", "0000", "0000"},  
    {"0000", "0000", "FFFF", "0000", "0000"}  
};  
  
  
	// Transpose the matrix from 3,5 to 5,3  
	string[,] transposed = matrix.Transpose()  // ****** not work, however?  

https://files.fm/f/ufs626uwf
174535-how-i-get-the-info-rows-colums-from-matrix.png

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,333 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,423 questions
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 26,916 Reputation points Microsoft Vendor
    2022-02-16T09:13:38.063+00:00

    Hi @Markus Freitag ,
    I tried your code, it should be the problem that the format does not correspond, you can try the following code.

    namespace WindowsFormsApp1.Core  
    {  
        public class ArrayExtensions<T>  
        {  
            public static T[,] Transpose(T[,] matrix)  
            {  
                var rows = matrix.GetLength(0);  
                var columns = matrix.GetLength(1);  
      
                var result = new T[columns, rows];  
      
                for (var c = 0; c < columns; c++)  
                {  
                    for (var r = 0; r < rows; r++)  
                    {  
                        result[c, r] = matrix[r, c];  
                    }  
                }      
                return result;  
            }  
        }          
        public class MatrixTest  
        {  
            public void TestMatrix()  
            {  
                string[,] matrix = new string[3,5]  
                {  
                    {"0000", "0000", "0000", "FFFF", "0000"},  
                    {"0000", "0000", "0000", "0000", "0000"},  
                    {"0000", "0000", "FFFF", "0000", "0000"}  
                };  
                var tMatrix = ArrayExtensions<string>.Transpose(matrix);  
                Console.WriteLine(tMatrix);  
            }  
        }  
    }  
    

    174895-1.jpg
    Edit:
    File path:C:***\WindowsFormsApp1\bin\Debug\text.txt

    public class MatrixTest  
        {  
            public void TestMatrix()  
            {  
                string[,] matrix = new string[3,5]  
                {  
                    {"0000", "0000", "0000", "FFFF", "0000"},  
                    {"0000", "0000", "0000", "0000", "0000"},  
                    {"0000", "0000", "FFFF", "0000", "0000"}  
                };  
              //  var tMatrix = ArrayExtensions<string>.Transpose(matrix);  
                var rows = matrix.GetLength(0);  
                var columns = matrix.GetLength(1);  
                using (TextWriter tw = new StreamWriter("text.txt"))  
                {  
                    tw.WriteLine("Original Matrix");  
                    for (int i = 0; i < rows; i++)  
                    {  
                        for (int j = 0; j < columns; j++)  
                        {  
                            tw.Write(matrix[i, j] + " ");  
                        }  
                        tw.WriteLine();  
                    }  
                    tw.WriteLine("Transpose Matrix");  
                    for (int j = 0; j < columns; j++)  
                    {  
                        for (int i = 0; i < rows; i++)  
                        {  
                            tw.Write(matrix[i, j] + " ");  
                        }  
                        tw.WriteLine();  
                    }                  
                }  
            }  
        }  
    

    175160-1.jpg
    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


2 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 58,761 Reputation points
    2022-02-15T17:51:32.54+00:00

    what is wrong with the result? the code and debug values look correct.

     {
         {"0000", "0000", "0000", "FFFF", "0000"},
         {"0000", "0000", "0000", "0000", "0000"},
         {"0000", "0000", "FFFF", "0000", "0000"}
     }
    
    //transposed:
    
     {
         {"0000", "0000", "0000"},
         {"0000", "0000", "0000"},
         {"0000", "0000", "FFFF"},
         {"FFFF", "0000", "0000"},
         {"0000", "0000", "0000"}
     }
    

  2. DINESH KUMAR VADIVEL 0 Reputation points
    2023-08-22T12:00:24.05+00:00

    Hi I tried the following way , which worked for me,

    static void Main(string[] args)
            {
                List<string> strArr = new List<string> { "RC1", "RC2", "RC3", 				   "RC4" };
                List<string> strArr2 = new List<string> { "RC5", "RC6", "RC7", "RC8" };
                List<string> strArr3 = new List<string> { "RC9", "RC10", "RC11", "RC12" };
                int columnCount = strArr.Count;
                List<List<string>> lsResult = new List<List<string>>();
                List<List<string>> lstStrs = new List<List<string>>() { strArr,strArr2,strArr3 };
                for (int i = 0; i < columnCount; i++)
                {
                    List<string> lstTemp = new List<string>();
                    for (int j = lstStrs.Count -1; j >=0; j--)
                    {
                        var temp = lstStrs[j];
                        lstTemp.Add(temp[i]);   
                        
                    }
                    lsResult.Add(lstTemp);
                }
    
                foreach (var lstStr in lsResult)
                {
                    foreach (var str in lstStr)
                    {
    
                        Console.Write(str + " ");                
                    }
                    Console.WriteLine();
                
                }
              
            }
    
    0 comments No comments