简体   繁体   中英

Create matrix from array with Math.Net

I've a list made by sublists of numbers. This is named biglist and it is:

biglist[0] = { 1, 2, 3, 4, 5 };
biglist[1] = { 5, 3, 3, 2, 1 };
biglist[2] = { 3, 4, 4, 5, 2 };

Now I want to create a matrix using these sublists where each sublist represents a column of the matrix . My final result has to be a matrix 5x3 in this way:

1 | 5 | 3   
---------
2 | 3 | 4   
---------  
3 | 3 | 4   
---------  
4 | 2 | 5   
---------  
5 | 1 | 2  

I know how to convert a list to array but I don't know how to assemble these arrays to create the matrix .

I think the package Math.Net could work for my purpose, but I don't understand how it's possible to do this with it.

MathNet limitation is you can use only Double , Single , Complex or Complex32 numeric types for that purpose.

using MathNet.Numerics.LinearAlgebra;

// ...

double[][] biglist = new double[3][];

biglist[0] = new double[] { 1, 2, 3, 4, 5 };
biglist[1] = new double[] { 5, 3, 3, 2, 1 };
biglist[2] = new double[] { 3, 4, 4, 5, 2 };

Matrix<double> matrix = Matrix<double>.Build.DenseOfColumns(biglist);
Console.WriteLine(matrix);

Gives:

DenseMatrix 5x3-Double
1  5  3
2  3  4
3  3  4
4  2  5
5  1  2

If I understand you very well you are trying to do something like this :

    public static int[,] GetMatrix(IReadOnlyList<int[]> bigList)
    {
        if (bigList.Count == 0) throw new ArgumentException("Value cannot be an empty collection.", nameof(bigList));

        var matrix = new int[bigList.Count, bigList[0].Length];

        for (var bigListIndex = 0; bigListIndex < bigList.Count; bigListIndex++)
        {
            int[] list = bigList[bigListIndex];

            for (var numberIndex = 0; numberIndex < list.Length; numberIndex++) matrix[bigListIndex, numberIndex] = list[numberIndex];
        }

        return matrix;
    }

    private static void Main(string[] args)
    {
        var biglist = new List<int[]>
        {
            new[] {1, 2, 3, 4, 5},
            new[] {5, 3, 3, 2, 1},
            new[] {3, 4, 4, 5, 2}
        };

        int[,] matrix = GetMatrix(biglist);

        for (var i = 0; i < matrix.GetLength(1); i++)
        {
            for (var j = 0; j < matrix.GetLength(0); j++)
                Console.Write($" {matrix[j, i]} ");
            Console.WriteLine();
        }


        Console.ReadKey();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM