I am reading data from a simple data file 'matrix.dat', eg:
1 2 3
4 5 6
7 8 9
I read through the file and save data points in a 2D array:
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]);
}
}
}
A you can see I am printing out the matrix twice for testing purposes. Once as I am reading the file and storing the data and then once again after the initial for loop has finished.
They should print out the exact same thing as I have done no manipulating to the 2D array 'MATRIX' in between the two for loops.
However, this is what gets printed out (when using the 'matrix.dat' file as above):
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
Any help would be greatly appreciated.
Just in case, this is the 'CheckSquare' function:
// 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);
}
}
If n is 3, the valid indices are 0,1,2 but you are declaring your matrix like this:
double MATRIX[n - 1][n - 1];
But should be declared like this:
double MATRIX[n][n];
If you are using loops like this:
for(i = 0; i < n; i++) /// Loop rows.
{
for(j = 0; j < n; j++) /// Loop columns.
{
Which iterate through 0, 1 and 2 when n == 3.