still on my Matrix class, here's a necessary helper method for getting the determinant:
In the attempt to debug, I've spelled out as much as possible in my determinant function (not using a cofactor function that I've also built but doing that by hand), which still doesn't work but looks like this:Code:template<typename T, int n> Matrix<T, n> Matrix<T, n>::scalar_multiply(const T& t) const { if (n > 0) { T arr[n][n]; for (int i = 0; i < n; ++i) // rows { for (int j = 0; j < n; ++j) // columns { arr[i][j] = t * content[i][j]; } } return Matrix<T, n>(arr); } else // bad value for n { std::cout << "Error! Matrix dimension must be > 0.\n"; return Matrix<T, n>(); } }
For purposes of comprehension, note that the at() function uses normal matrix indexing (first row/col=1) whereas the content[][] array is using array indexing (first row/col = 0).Code:template<typename T, int n> T Matrix<T, n>::determinant() const { if (n == 1) return content[0][0]; else if (n > 1) // recursive part { T det = 0; // use Laplace expansion on first row for (int i = 1; i <= n; ++i) { Matrix<T, n - 1> temp; // using this->cofactor(1, i) gives a type conversion error // problem seems to come from decrementing n (?) // determine temp Matrix for each column i for (int j = 1; j <= n - 1; ++j) // rows of temp { for (int k = 1; k <= n - 1; ++k) { if (k < i) temp.at(j, k) = content[j][k - 1]; else temp.at(j, k) = content[j][k]; } } if ((i + 1) % 2) temp = -temp; temp = temp.scalar_multiply(content[0][i - 1]); det += temp.determinant(); } return det; } // */ else // abnormal case where n < 1 return 0; }
A few notes (in case it's not immediately obvious to you guys what's wrong):
1) If I comment out the recursive line det += temp.determinant(); it compiles (just obviously not giving the desired value).
2) The error message I get on this variation is somewhat strange, namely that in line 29 'arr' is missing a subscript. Verbatim:
This is of course debugging output and not code even though I put it in a code box. In any case, line 29 is completely innocuous, namely the prototype for constructing a Matrix from an array (which works fine until the recursive determinant() function gets used):Code:\matrix.h(29) : error C2087: 'arr' : missing subscript 1> c:\users\marshall\documents\mf_program\cpp\matrix\matrix\matrix.h(382) : see reference to class template instantiation 'Matrix<T,n>' being compiled 1> with 1> [ 1> T=double, 1> n=0 1> ]
But the error output indicates that the recursion has gotten down to n = 0 when the error occurs--and, yes, that would make for an error. But I thought I had created an endpoint (or starting point, if you will) for the recursion in the first if statement, where I give determinant() an explicit value when n == 1. That is, I thought I'd set it up so that we wouldn't ever get to n == 0 unless we start with a bad n value.Code:Matrix(const T arr[][n]);
So... why is this happening and how do I fix it?



LinkBack URL
About LinkBacks


