如何在C#中构造具有所需性质的矩阵

本文关键字: | 更新日期: 2023-09-27 17:59:29

我需要构造一个具有((X.size)^ncol)X ncol维度的矩阵。其中X是一个数组,X.size是该数组的大小

ncol表示列数。

给定的输入是一个数组(比如"X")和所需矩阵的列数(比如"ncol")。

我认为写下属性会造成混乱,所以我想举几个给定输入的期望矩阵的例子:

示例1:

输入:数组X=[1,2,3],所需列数为2

那么我的输出应该是

    Var1 Var2
 [1,]    1    1
 [2,]    2    1
 [3,]    3    1
 [4,]    1    2
 [5,]    2    2
 [6,]    3    2
 [7,]    1    3
 [8,]    2    3
 [9,]    3    3

示例2:

输入:数组X=[1,2,3],所需列数为3

     Var1 Var2 Var3
 [1,]    1    1    1
 [2,]    2    1    1
 [3,]    3    1    1
 [4,]    1    2    1
 [5,]    2    2    1
 [6,]    3    2    1
 [7,]    1    3    1
 [8,]    2    3    1
 [9,]    3    3    1
[10,]    1    1    2
[11,]    2    1    2
[12,]    3    1    2
[13,]    1    2    2
[14,]    2    2    2
[15,]    3    2    2
[16,]    1    3    2
[17,]    2    3    2
[18,]    3    3    2
[19,]    1    1    3
[20,]    2    1    3
[21,]    3    1    3
[22,]    1    2    3
[23,]    2    2    3
[24,]    3    2    3
[25,]    1    3    3
[26,]    2    3    3
[27,]    3    3    3

示例3:

输入:数组X=[1,2,3],所需列数为1

那么期望的输出应该是

    [,1]
[1,]    1
[2,]    2
[3,]    3

有什么建议吗?

谢谢。

如何在C#中构造具有所需性质的矩阵

您基本上想要枚举给定数组中nCols符号的所有组合。

通过以下观察可以很容易地做到这一点:第一列中的元素重复一次。第二列中的元素重复symbols.Length次。在第三列symbols.Length^2等。

填充这个矩阵可以在几个嵌套循环中完成,如下所示:

// Calculate the needed number of rows
int nRows = (int)Math.Pow(symbols.Length, nCols);
// Allocate memory for the matrix
int[,] matrix = new int[nRows, nCols];
// The first column repeats elements exactly once
int repeatedElementsInCol = 1;
//Successively fill all columns
for (int col = 0; col < nCols; ++col)
{
    int row = 0;
    // Fill every row
    while(row < nRows)
    {
        // Write each symbol to the matrix ...
        foreach (var symbol in symbols)
            // ... with the specified number of repetitions
            for (int repetition = 0; repetition < repeatedElementsInCol; ++repetition)
                matrix[row++, col] = symbol;
    }
    // The next column repeats elements symbols.Length times as often
    repeatedElementsInCol *= symbols.Length;
}

这给出了nCols = 3symbols = { 1, 2, 3 } 的以下矩阵

1  1  1
2  1  1
3  1  1
1  2  1
2  2  1
3  2  1
1  3  1
2  3  1
3  3  1
1  1  2
2  1  2
3  1  2
1  2  2
2  2  2
3  2  2
1  3  2
2  3  2
3  3  2
1  1  3
2  1  3
3  1  3
1  2  3
2  2  3
3  2  3
1  3  3
2  3  3
3  3  3
相关文章:
  • 没有找到相关文章