如何像在C#中使用多维数组那样初始化矩阵对象?
我必须创建一个矩阵类,以便在我的神经网络项目中使用它。在创建矩阵对象时,它的工作原理与多维数组类似,我如何实现这一点 基本上我有一个矩阵类,它看起来像这样:如何像在C#中使用多维数组那样初始化矩阵对象?,c#,arrays,matrix,multidimensional-array,neural-network,C#,Arrays,Matrix,Multidimensional Array,Neural Network,我必须创建一个矩阵类,以便在我的神经网络项目中使用它。在创建矩阵对象时,它的工作原理与多维数组类似,我如何实现这一点 基本上我有一个矩阵类,它看起来像这样: class Matrix { private int rows; private int size; private int columns; private double[,] _inMatrix; public double this[int row, int col] {
class Matrix
{
private int rows;
private int size;
private int columns;
private double[,] _inMatrix;
public double this[int row, int col]
{
get
{
return _inMatrix[row, col];
}
set
{
_inMatrix[row, col] = value;
}
}
public Matrix(int row, int col)
{
rows = row;
columns = col;
size = row * col;
_inMatrix = new double[rows, columns];
}
public Matrix()
{
}
//and bunch of operations
当我知道矩阵的行和列时,它就像一个符咒,但我希望能够在开始或以后设置值。
当我创建矩阵对象时,我是这样做的:
Matrix m1=new Matrix(row, column)
我想做的是能够像使用数组一样在一开始就设置值。
我知道,在C#中,我们就是这样初始化多维数组的:
double[,] 2Darray = new double[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
//or
int[,] 2Darray;
2Darray = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
我怎样才能达到类似的效果呢?要事先设定这些值,你可以按照自己的建议去做 只需在空构造函数中填入所需的值即可
public Matrix()
{
_inMatrix = new double[ , ] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
}
在那之后,你可以用你想要的值创建一个新的矩阵
Matrix m1=new Matrix()
您甚至可以创建一个矩阵,希望在其中初始化矩阵并将其传递给另一个构造函数
public Matrix(double[,] _NewMatrix)
{
_inMatrix = _NewMatrix;
}
并称之为
double[,] NewMatrix = new double[ , ] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
Matrix m_Matrix = new Matrix( NewMatrix );
可能是这样的,有
隐式操作符
能够做矩阵m=newdouble[,]{{1,1},{2,3}代码>。此外,您不需要\u行
和\u列
,因为您可以轻松地从底层多维数组(GetLength(int-dimension)
)中提取它们
尝试更改\u inMatrix=new double[行、列]代码>到\u inMatrix=new double[,]{}代码>您可以轻松地将数组传递到构造函数中,并以这种方式创建矩阵对象。请通读
class Matrix
{
private double[,] _inMatrix;
public double this[int row, int col]
{
get => _inMatrix[row, col];
set => _inMatrix[row, col] = value;
}
public Matrix(double[,] a) => Initialize(a);
//and bunch of operations
private void Initialize(double[,] a) => _inMatrix = a;
public static implicit operator Matrix(double[,] a) => new Matrix(a);
}