我正在从一个简单的数据文件'matrix.dat'中读取数据,例如:
1 2 3
4 5 6
7 8 9
我通读文件并将数据点保存在2D数组中:
else /// Read data from file.
{
// Check matrix is square and find number of columns/rows.
n = CheckSquare(matrixData); /// n = dimension of square matrix
fprintf(stdout, "n = %d\n", n); /// TESTING ///
if(n != 0) /// Matrix is square.
{
int i, j; /// i = rows, j = columns.
double MATRIX[n - 1][n - 1]; /// Declare 2D array of size n x n.
// Loop through file "matrix.dat" and store data into 2D array "MATRIX".
for(i = 0; i < n; i++) /// Loop rows.
{
for(j = 0; j < n; j++) /// Loop columns.
{
fscanf(matrixData, "%lf", &MATRIX[i][j]); /// Store data point as matrix element.
fprintf(stdout, "[%d][%d] = %lf\n", i, j, MATRIX[i][j]); ///TESTING ///
}
}
// Calculate the determinant of matrix "MATRIX".
///det = Determinant(n, MATRIX); /// COMMENT OUT ///
///fprintf(stdout, "Determinant = %lf\n", det); /// COMMENT OUT ///
for(i = 0; i < n; i++) /// Loop rows.
{
for(j = 0; j < n; j++) /// Loop columns.
{
fprintf(stdout, "[%d][%d] = %lf\n", i, j, MATRIX[i][j]);
}
}
}
你可以看到我打印矩阵两次用于测试目的。一旦我正在读取文件并存储数据,然后在初始for循环完成后再次。
它们应该打印出完全相同的东西,因为我没有操纵两个for循环之间的2D数组'MATRIX'。
然而,这是打印出来的(当使用上面的'matrix.dat'文件时):
n = 3
[0][0] = 1.000000
[0][1] = 2.000000
[0][2] = 3.000000
[1][0] = 4.000000
[1][1] = 5.000000
[1][2] = 6.000000
[2][0] = 7.000000
[2][1] = 8.000000
[2][2] = 9.000000
[0][0] = 1.000000
[0][1] = 2.000000
[0][2] = 4.000000
[1][0] = 4.000000
[1][1] = 5.000000
[1][2] = 5.000000
[2][0] = 5.000000
[2][1] = 8.000000
[2][2] = 9.000000
非常感谢任何帮助。
以防万一,这是'CheckSquare'功能:
// Checks if matrix is square and returns the dimension if TRUE.
// Otherwise returns 0.
int CheckSquare(FILE* m)
{
int dim; /// Dimension of matrix.
int dataNum = 0; /// Holds number of data points in file "matrixData".
double temp; /// Temporary variable to hold double data.
// Check matrix is square and find number of columns/rows.
while(fscanf(m, "%lf", &temp) != EOF) /// Data can still be read from file "matrixData".
{
dataNum++; /// Adds to number of data points.
}
rewind(m); /// Sets the position indicator to the beginning of the file "matrixData".
dim = sqrt(dataNum); /// Number of columns and rows if 'dataNum' is perfect square.
if(dim*dim == dataNum) /// Matrix is square.
{
return(dim);
}
else
{
return(0);
}
}
答案 0 :(得分:2)
如果n为3,则有效索引为0,1,2,但您声明的矩阵是这样的:
double MATRIX[n - 1][n - 1];
但应该这样说:
double MATRIX[n][n];
如果你使用这样的循环:
for(i = 0; i < n; i++) /// Loop rows.
{
for(j = 0; j < n; j++) /// Loop columns.
{
当n == 3时,迭代0,1和2.