我有一个使用double的矩阵乘法实验室的代码,我想将它与使用List< List< double>>的实现进行比较
public static Matrix operator *(Matrix a, Matrix b)
{
if (a.Width != b.Height)
{
throw new InvalidOperationException();
}
double[,] result = new double[a.Height, b.Width];
for (int i = 0; i < a.Height; i++)
{
for (int j = 0; j < b.Width; j++)
{
for (int k = 0; k < a.Width; k++)
result[i, j] += a[i, k] * b[k, j];
}
}
return new Matrix(result);
}这里的“‘result”有正确的数据:
输入矩阵A:
1.000 2.000 3.000 1.000
2.000 3.000 3.000 1.000
输入矩阵B:
1.000 0.000 0.000 0.000
0.000 1.000 0.000 0.000
0.000 0.000 1.000 0.000
2.000 3.000 0.000 1.000
矩阵乘积A*B
3.000 5.000 3.000 1.000
4.000 6.000 3.000 1.000
正在将其更改为列表...
public List<List<double>> matrix;
public double this[int x, int y]
{
get { return matrix[x][y]; }
set { matrix[x][y] = value; }
}
public static Matrix operator *(Matrix a, Matrix b)
{
if (a.Width != b.Height)
{
throw new InvalidOperationException();
}
Matrix result = new Matrix(a.Height, b.Width);
for (int i = 0; i < a.Height; i++)
{
for (int j = 0; j < b.Width; j++)
{
for (int k = 0; k < a.Width; k++)
result[i, j] += a[i, k] * b[k, j];
}
}
return result;
}使用相同的数据,现在的结果是:
7 6
7 6
编辑:构造函数是:
public Matrix(int height, int width)
{
List<List<double>> points = new List<List<double>>();
List<double> row = new List<double>();
for (int i = 0; i < width; i++)
{
row.Add(0.0d);
}
for (int i = 0; i < height; i++)
{
points.Add(row);
}
matrix = points;
}它看起来运行得很好,一切都初始化为0.0
我的问题是,为什么数学会在两种存储值的方式之间发生变化。
发布于 2009-11-11 09:34:29
问题出在你的矩阵构造器上。您将"points“中的每个”行“都设置为相同的实例。
尝试将构造函数更改为:
public Matrix(int height, int width)
{
List<List<double>> points = new List<List<double>>(height); // Might as well set the default capacity...
for (int j = 0; j < height; j++)
{
List<double> row = new List<double>(width);
for (int i = 0; i < width; i++)
{
row.Add(0.0d);
}
points.Add(row);
}
matrix = points;
}也就是说,对于矩阵,除非您尝试实现稀疏矩阵,否则多维数组更有意义。只有当您希望允许列表增长时,使用列表列表才更有意义。在您的情况下,您预先知道大小,所以使用数组可能是更好的选择。
发布于 2009-11-11 09:33:07
好吧,构造器是错误的。这是因为矩阵中的所有行都指向一个对象。当您更改一行中的数据时,实际上是更改了所有行中的数据。
这样更正它。
public Matrix(int height, int width)
{
List<List<double>> points = new List<List<double>>();
for (int i = 0; i < height; i++)
{
List<double> row = new List<double>();
for (int i = 0; i < width; i++)
{
row.Add(0.0d);
}
points.Add(row);
}
matrix = points;
}https://stackoverflow.com/questions/1712346
复制相似问题