3 * Implementation of symbolic matrices */
6 * GiNaC Copyright (C) 1999-2000 Johannes Gutenberg University Mainz, Germany
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
37 #ifndef NO_NAMESPACE_GINAC
39 #endif // ndef NO_NAMESPACE_GINAC
41 GINAC_IMPLEMENT_REGISTERED_CLASS(matrix, basic)
44 // default constructor, destructor, copy constructor, assignment operator
50 /** Default ctor. Initializes to 1 x 1-dimensional zero-matrix. */
52 : inherited(TINFO_matrix), row(1), col(1)
54 debugmsg("matrix default constructor",LOGLEVEL_CONSTRUCT);
60 debugmsg("matrix destructor",LOGLEVEL_DESTRUCT);
63 matrix::matrix(const matrix & other)
65 debugmsg("matrix copy constructor",LOGLEVEL_CONSTRUCT);
69 const matrix & matrix::operator=(const matrix & other)
71 debugmsg("matrix operator=",LOGLEVEL_ASSIGNMENT);
81 void matrix::copy(const matrix & other)
83 inherited::copy(other);
86 m = other.m; // STL's vector copying invoked here
89 void matrix::destroy(bool call_parent)
91 if (call_parent) inherited::destroy(call_parent);
100 /** Very common ctor. Initializes to r x c-dimensional zero-matrix.
102 * @param r number of rows
103 * @param c number of cols */
104 matrix::matrix(unsigned r, unsigned c)
105 : inherited(TINFO_matrix), row(r), col(c)
107 debugmsg("matrix constructor from unsigned,unsigned",LOGLEVEL_CONSTRUCT);
108 m.resize(r*c, _ex0());
113 /** Ctor from representation, for internal use only. */
114 matrix::matrix(unsigned r, unsigned c, const exvector & m2)
115 : inherited(TINFO_matrix), row(r), col(c), m(m2)
117 debugmsg("matrix constructor from unsigned,unsigned,exvector",LOGLEVEL_CONSTRUCT);
124 /** Construct object from archive_node. */
125 matrix::matrix(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
127 debugmsg("matrix constructor from archive_node", LOGLEVEL_CONSTRUCT);
128 if (!(n.find_unsigned("row", row)) || !(n.find_unsigned("col", col)))
129 throw (std::runtime_error("unknown matrix dimensions in archive"));
130 m.reserve(row * col);
131 for (unsigned int i=0; true; i++) {
133 if (n.find_ex("m", e, sym_lst, i))
140 /** Unarchive the object. */
141 ex matrix::unarchive(const archive_node &n, const lst &sym_lst)
143 return (new matrix(n, sym_lst))->setflag(status_flags::dynallocated);
146 /** Archive the object. */
147 void matrix::archive(archive_node &n) const
149 inherited::archive(n);
150 n.add_unsigned("row", row);
151 n.add_unsigned("col", col);
152 exvector::const_iterator i = m.begin(), iend = m.end();
160 // functions overriding virtual functions from bases classes
165 basic * matrix::duplicate() const
167 debugmsg("matrix duplicate",LOGLEVEL_DUPLICATE);
168 return new matrix(*this);
171 void matrix::print(ostream & os, unsigned upper_precedence) const
173 debugmsg("matrix print",LOGLEVEL_PRINT);
175 for (unsigned r=0; r<row-1; ++r) {
177 for (unsigned c=0; c<col-1; ++c) {
178 os << m[r*col+c] << ",";
180 os << m[col*(r+1)-1] << "]], ";
183 for (unsigned c=0; c<col-1; ++c) {
184 os << m[(row-1)*col+c] << ",";
186 os << m[row*col-1] << "]] ]]";
189 void matrix::printraw(ostream & os) const
191 debugmsg("matrix printraw",LOGLEVEL_PRINT);
192 os << "matrix(" << row << "," << col <<",";
193 for (unsigned r=0; r<row-1; ++r) {
195 for (unsigned c=0; c<col-1; ++c) {
196 os << m[r*col+c] << ",";
198 os << m[col*(r-1)-1] << "),";
201 for (unsigned c=0; c<col-1; ++c) {
202 os << m[(row-1)*col+c] << ",";
204 os << m[row*col-1] << "))";
207 /** nops is defined to be rows x columns. */
208 unsigned matrix::nops() const
213 /** returns matrix entry at position (i/col, i%col). */
214 ex matrix::op(int i) const
219 /** returns matrix entry at position (i/col, i%col). */
220 ex & matrix::let_op(int i)
225 /** expands the elements of a matrix entry by entry. */
226 ex matrix::expand(unsigned options) const
228 exvector tmp(row*col);
229 for (unsigned i=0; i<row*col; ++i) {
230 tmp[i]=m[i].expand(options);
232 return matrix(row, col, tmp);
235 /** Search ocurrences. A matrix 'has' an expression if it is the expression
236 * itself or one of the elements 'has' it. */
237 bool matrix::has(const ex & other) const
239 GINAC_ASSERT(other.bp!=0);
241 // tautology: it is the expression itself
242 if (is_equal(*other.bp)) return true;
244 // search all the elements
245 for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
246 if ((*r).has(other)) return true;
251 /** evaluate matrix entry by entry. */
252 ex matrix::eval(int level) const
254 debugmsg("matrix eval",LOGLEVEL_MEMBER_FUNCTION);
256 // check if we have to do anything at all
257 if ((level==1)&&(flags & status_flags::evaluated))
261 if (level == -max_recursion_level)
262 throw (std::runtime_error("matrix::eval(): recursion limit exceeded"));
264 // eval() entry by entry
265 exvector m2(row*col);
267 for (unsigned r=0; r<row; ++r) {
268 for (unsigned c=0; c<col; ++c) {
269 m2[r*col+c] = m[r*col+c].eval(level);
273 return (new matrix(row, col, m2))->setflag(status_flags::dynallocated |
274 status_flags::evaluated );
277 /** evaluate matrix numerically entry by entry. */
278 ex matrix::evalf(int level) const
280 debugmsg("matrix evalf",LOGLEVEL_MEMBER_FUNCTION);
282 // check if we have to do anything at all
287 if (level == -max_recursion_level) {
288 throw (std::runtime_error("matrix::evalf(): recursion limit exceeded"));
291 // evalf() entry by entry
292 exvector m2(row*col);
294 for (unsigned r=0; r<row; ++r) {
295 for (unsigned c=0; c<col; ++c) {
296 m2[r*col+c] = m[r*col+c].evalf(level);
299 return matrix(row, col, m2);
304 int matrix::compare_same_type(const basic & other) const
306 GINAC_ASSERT(is_exactly_of_type(other, matrix));
307 const matrix & o = static_cast<matrix &>(const_cast<basic &>(other));
309 // compare number of rows
311 return row < o.rows() ? -1 : 1;
313 // compare number of columns
315 return col < o.cols() ? -1 : 1;
317 // equal number of rows and columns, compare individual elements
319 for (unsigned r=0; r<row; ++r) {
320 for (unsigned c=0; c<col; ++c) {
321 cmpval = ((*this)(r,c)).compare(o(r,c));
322 if (cmpval!=0) return cmpval;
325 // all elements are equal => matrices are equal;
330 // non-virtual functions in this class
337 * @exception logic_error (incompatible matrices) */
338 matrix matrix::add(const matrix & other) const
340 if (col != other.col || row != other.row)
341 throw (std::logic_error("matrix::add(): incompatible matrices"));
343 exvector sum(this->m);
344 exvector::iterator i;
345 exvector::const_iterator ci;
346 for (i=sum.begin(), ci=other.m.begin();
351 return matrix(row,col,sum);
355 /** Difference of matrices.
357 * @exception logic_error (incompatible matrices) */
358 matrix matrix::sub(const matrix & other) const
360 if (col != other.col || row != other.row)
361 throw (std::logic_error("matrix::sub(): incompatible matrices"));
363 exvector dif(this->m);
364 exvector::iterator i;
365 exvector::const_iterator ci;
366 for (i=dif.begin(), ci=other.m.begin();
371 return matrix(row,col,dif);
375 /** Product of matrices.
377 * @exception logic_error (incompatible matrices) */
378 matrix matrix::mul(const matrix & other) const
380 if (col != other.row)
381 throw (std::logic_error("matrix::mul(): incompatible matrices"));
383 exvector prod(row*other.col);
385 for (unsigned r1=0; r1<row; ++r1) {
386 for (unsigned c=0; c<col; ++c) {
387 if (m[r1*col+c].is_zero())
389 for (unsigned r2=0; r2<other.col; ++r2)
390 prod[r1*other.col+r2] += m[r1*col+c] * other.m[c*other.col+r2];
393 return matrix(row, other.col, prod);
397 /** operator() to access elements.
399 * @param ro row of element
400 * @param co column of element
401 * @exception range_error (index out of range) */
402 const ex & matrix::operator() (unsigned ro, unsigned co) const
404 if (ro<0 || ro>=row || co<0 || co>=col)
405 throw (std::range_error("matrix::operator(): index out of range"));
411 /** Set individual elements manually.
413 * @exception range_error (index out of range) */
414 matrix & matrix::set(unsigned ro, unsigned co, ex value)
416 if (ro<0 || ro>=row || co<0 || co>=col)
417 throw (std::range_error("matrix::set(): index out of range"));
419 ensure_if_modifiable();
420 m[ro*col+co] = value;
425 /** Transposed of an m x n matrix, producing a new n x m matrix object that
426 * represents the transposed. */
427 matrix matrix::transpose(void) const
429 exvector trans(col*row);
431 for (unsigned r=0; r<col; ++r)
432 for (unsigned c=0; c<row; ++c)
433 trans[r*row+c] = m[c*col+r];
435 return matrix(col,row,trans);
439 /** Determinant of square matrix. This routine doesn't actually calculate the
440 * determinant, it only implements some heuristics about which algorithm to
441 * call. If all the elements of the matrix are elements of an integral domain
442 * the determinant is also in that integral domain and the result is expanded
443 * only. If one or more elements are from a quotient field the determinant is
444 * usually also in that quotient field and the result is normalized before it
445 * is returned. This implies that the determinant of the symbolic 2x2 matrix
446 * [[a/(a-b),1],[b/(a-b),1]] is returned as unity. (In this respect, it
447 * behaves like MapleV and unlike Mathematica.)
449 * @return the determinant as a new expression
450 * @exception logic_error (matrix not square) */
451 ex matrix::determinant(void) const
454 throw (std::logic_error("matrix::determinant(): matrix not square"));
455 GINAC_ASSERT(row*col==m.capacity());
456 if (this->row==1) // continuation would be pointless
459 // Gather some information about the matrix:
460 bool numeric_flag = true;
461 bool normal_flag = false;
462 unsigned sparse_count = 0; // count non-zero elements
463 for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
466 if (!(*r).info(info_flags::numeric))
467 numeric_flag = false;
468 if ((*r).info(info_flags::rational_function) &&
469 !(*r).info(info_flags::crational_polynomial))
473 // Purely numeric matrix handled by Gauss elimination
477 int sign = tmp.gauss_elimination();
478 for (int d=0; d<row; ++d)
479 det *= tmp.m[d*col+d];
483 // Does anybody know when a matrix is really sparse?
484 // Maybe <~row/2.2 nonzero elements average in a row?
485 if (5*sparse_count<=row*col) {
489 sign = tmp.fraction_free_elimination(true);
491 return (sign*tmp.m[row*col-1]).normal();
493 return (sign*tmp.m[row*col-1]).expand();
496 // Now come the minor expansion schemes. We always develop such that the
497 // smallest minors (i.e, the trivial 1x1 ones) are on the rightmost column.
498 // For this to be efficient it turns out that the emptiest columns (i.e.
499 // the ones with most zeros) should be the ones on the right hand side.
500 // Therefore we presort the columns of the matrix:
501 typedef pair<unsigned,unsigned> uintpair; // # of zeros, column
502 vector<uintpair> c_zeros; // number of zeros in column
503 for (unsigned c=0; c<col; ++c) {
505 for (unsigned r=0; r<row; ++r)
506 if (m[r*col+c].is_zero())
508 c_zeros.push_back(uintpair(acc,c));
510 sort(c_zeros.begin(),c_zeros.end());
511 vector<unsigned> pre_sort; // unfortunately vector<uintpair> can't be used
512 // for permutation_sign.
513 for (vector<uintpair>::iterator i=c_zeros.begin(); i!=c_zeros.end(); ++i)
514 pre_sort.push_back(i->second);
515 int sign = permutation_sign(pre_sort);
516 exvector result(row*col); // represents sorted matrix
518 for (vector<unsigned>::iterator i=pre_sort.begin();
521 for (unsigned r=0; r<row; ++r)
522 result[r*col+c] = m[r*col+(*i)];
526 return sign*matrix(row,col,result).determinant_minor().normal();
527 return sign*matrix(row,col,result).determinant_minor();
531 /** Trace of a matrix. The result is normalized if it is in some quotient
532 * field and expanded only otherwise. This implies that the trace of the
533 * symbolic 2x2 matrix [[a/(a-b),x],[y,b/(b-a)]] is recognized to be unity.
535 * @return the sum of diagonal elements
536 * @exception logic_error (matrix not square) */
537 ex matrix::trace(void) const
540 throw (std::logic_error("matrix::trace(): matrix not square"));
541 GINAC_ASSERT(row*col==m.capacity());
544 for (unsigned r=0; r<col; ++r)
547 if (tr.info(info_flags::rational_function) &&
548 !tr.info(info_flags::crational_polynomial))
555 /** Characteristic Polynomial. Following mathematica notation the
556 * characteristic polynomial of a matrix M is defined as the determiant of
557 * (M - lambda * 1) where 1 stands for the unit matrix of the same dimension
558 * as M. Note that some CASs define it with a sign inside the determinant
559 * which gives rise to an overall sign if the dimension is odd. This method
560 * returns the characteristic polynomial collected in powers of lambda as a
563 * @return characteristic polynomial as new expression
564 * @exception logic_error (matrix not square)
565 * @see matrix::determinant() */
566 ex matrix::charpoly(const symbol & lambda) const
569 throw (std::logic_error("matrix::charpoly(): matrix not square"));
571 bool numeric_flag = true;
572 for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
573 if (!(*r).info(info_flags::numeric)) {
574 numeric_flag = false;
578 // The pure numeric case is traditionally rather common. Hence, it is
579 // trapped and we use Leverrier's algorithm which goes as row^3 for
580 // every coefficient. The expensive part is the matrix multiplication.
584 ex poly = power(lambda,row)-c*power(lambda,row-1);
585 for (unsigned i=1; i<row; ++i) {
586 for (unsigned j=0; j<row; ++j)
589 c = B.trace()/ex(i+1);
590 poly -= c*power(lambda,row-i-1);
599 for (unsigned r=0; r<col; ++r)
600 M.m[r*col+r] -= lambda;
602 return M.determinant().collect(lambda);
606 /** Inverse of this matrix.
608 * @return the inverted matrix
609 * @exception logic_error (matrix not square)
610 * @exception runtime_error (singular matrix) */
611 matrix matrix::inverse(void) const
614 throw (std::logic_error("matrix::inverse(): matrix not square"));
617 // set tmp to the unit matrix
618 for (unsigned i=0; i<col; ++i)
619 tmp.m[i*col+i] = _ex1();
621 // create a copy of this matrix
623 for (unsigned r1=0; r1<row; ++r1) {
624 int indx = cpy.pivot(r1);
626 throw (std::runtime_error("matrix::inverse(): singular matrix"));
628 if (indx != 0) { // swap rows r and indx of matrix tmp
629 for (unsigned i=0; i<col; ++i) {
630 tmp.m[r1*col+i].swap(tmp.m[indx*col+i]);
633 ex a1 = cpy.m[r1*col+r1];
634 for (unsigned c=0; c<col; ++c) {
635 cpy.m[r1*col+c] /= a1;
636 tmp.m[r1*col+c] /= a1;
638 for (unsigned r2=0; r2<row; ++r2) {
640 ex a2 = cpy.m[r2*col+r1];
641 for (unsigned c=0; c<col; ++c) {
642 cpy.m[r2*col+c] -= a2 * cpy.m[r1*col+c];
643 tmp.m[r2*col+c] -= a2 * tmp.m[r1*col+c];
652 /** Solve a set of equations for an m x n matrix by fraction-free Gaussian
653 * elimination. Based on algorithm 9.1 from 'Algorithms for Computer Algebra'
654 * by Keith O. Geddes et al.
656 * @param vars n x p matrix
657 * @param rhs m x p matrix
658 * @exception logic_error (incompatible matrices)
659 * @exception runtime_error (singular matrix) */
660 matrix matrix::fraction_free_elim(const matrix & vars,
661 const matrix & rhs) const
663 // FIXME: use implementation of matrix::fraction_free_elimination
664 if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col))
665 throw (std::logic_error("matrix::fraction_free_elim(): incompatible matrices"));
667 matrix a(*this); // make a copy of the matrix
668 matrix b(rhs); // make a copy of the rhs vector
670 // given an m x n matrix a, reduce it to upper echelon form
677 // eliminate below row r, with pivot in column k
678 for (unsigned k=0; (k<n)&&(r<m); ++k) {
679 // find a nonzero pivot
681 for (p=r; (p<m)&&(a.m[p*a.cols()+k].is_zero()); ++p) {}
686 for (unsigned j=k; j<n; ++j)
687 a.m[p*a.cols()+j].swap(a.m[r*a.cols()+j]);
688 a.m[p*a.cols()].swap(a.m[r*a.cols()]);
689 // keep track of sign changes due to row exchange
692 for (unsigned i=r+1; i<m; ++i) {
693 for (unsigned j=k+1; j<n; ++j) {
694 a.set(i,j,(a.m[r*a.cols()+k]*a.m[i*a.cols()+j]
695 -a.m[r*a.cols()+j]*a.m[i*a.cols()+k])/divisor);
696 a.set(i,j,a.m[i*a.cols()+j].normal());
698 b.set(i,0,(a.m[r*a.cols()+k]*b.m[i*b.cols()]
699 -b.m[r*b.cols()]*a.m[i*a.cols()+k])/divisor);
700 b.set(i,0,b.m[i*b.cols()].normal());
703 divisor = a.m[r*a.cols()+k];
708 #ifdef DO_GINAC_ASSERT
709 // test if we really have an upper echelon matrix
710 int zero_in_last_row = -1;
711 for (unsigned r=0; r<m; ++r) {
712 int zero_in_this_row=0;
713 for (unsigned c=0; c<n; ++c) {
714 if (a.m[r*a.cols()+c].is_zero())
719 GINAC_ASSERT((zero_in_this_row>zero_in_last_row)||(zero_in_this_row=n));
720 zero_in_last_row = zero_in_this_row;
722 #endif // def DO_GINAC_ASSERT
726 unsigned last_assigned_sol = n+1;
727 for (int r=m-1; r>=0; --r) {
728 unsigned first_non_zero = 1;
729 while ((first_non_zero<=n)&&(a.m[r*a.cols()+(first_non_zero-1)].is_zero()))
731 if (first_non_zero>n) {
732 // row consists only of zeroes, corresponding rhs must be 0 as well
733 if (!b.m[r*b.cols()].is_zero()) {
734 throw (std::runtime_error("matrix::fraction_free_elim(): singular matrix"));
737 // assign solutions for vars between first_non_zero+1 and
738 // last_assigned_sol-1: free parameters
739 for (unsigned c=first_non_zero; c<last_assigned_sol-1; ++c)
740 sol.set(c,0,vars.m[c*vars.cols()]);
741 ex e = b.m[r*b.cols()];
742 for (unsigned c=first_non_zero; c<n; ++c)
743 e -= a.m[r*a.cols()+c]*sol.m[c*sol.cols()];
744 sol.set(first_non_zero-1,0,
745 (e/a.m[r*a.cols()+(first_non_zero-1)]).normal());
746 last_assigned_sol = first_non_zero;
749 // assign solutions for vars between 1 and
750 // last_assigned_sol-1: free parameters
751 for (unsigned c=0; c<last_assigned_sol-1; ++c)
752 sol.set(c,0,vars.m[c*vars.cols()]);
754 #ifdef DO_GINAC_ASSERT
755 // test solution with echelon matrix
756 for (unsigned r=0; r<m; ++r) {
758 for (unsigned c=0; c<n; ++c)
759 e += a.m[r*a.cols()+c]*sol.m[c*sol.cols()];
760 if (!(e-b.m[r*b.cols()]).normal().is_zero()) {
762 cout << "b(" << r <<",0)=" << b.m[r*b.cols()] << endl;
763 cout << "diff=" << (e-b.m[r*b.cols()]).normal() << endl;
765 GINAC_ASSERT((e-b.m[r*b.cols()]).normal().is_zero());
768 // test solution with original matrix
769 for (unsigned r=0; r<m; ++r) {
771 for (unsigned c=0; c<n; ++c)
772 e += this->m[r*cols()+c]*sol.m[c*sol.cols()];
774 if (!(e-rhs.m[r*rhs.cols()]).normal().is_zero()) {
775 cout << "e==" << e << endl;
778 cout << "e.normal()=" << en << endl;
780 cout << "rhs(" << r <<",0)=" << rhs.m[r*rhs.cols()] << endl;
781 cout << "diff=" << (e-rhs.m[r*rhs.cols()]).normal() << endl;
784 ex xxx = e - rhs.m[r*rhs.cols()];
785 cerr << "xxx=" << xxx << endl << endl;
787 GINAC_ASSERT((e-rhs.m[r*rhs.cols()]).normal().is_zero());
789 #endif // def DO_GINAC_ASSERT
794 /** Solve a set of equations for an m x n matrix.
796 * @param vars n x p matrix
797 * @param rhs m x p matrix
798 * @exception logic_error (incompatible matrices)
799 * @exception runtime_error (singular matrix) */
800 matrix matrix::solve(const matrix & vars,
801 const matrix & rhs) const
803 if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col))
804 throw (std::logic_error("matrix::solve(): incompatible matrices"));
806 throw (std::runtime_error("FIXME: need implementation."));
809 /** Old and obsolete interface: */
810 matrix matrix::old_solve(const matrix & v) const
812 if ((v.row != col) || (col != v.row))
813 throw (std::logic_error("matrix::solve(): incompatible matrices"));
815 // build the augmented matrix of *this with v attached to the right
816 matrix tmp(row,col+v.col);
817 for (unsigned r=0; r<row; ++r) {
818 for (unsigned c=0; c<col; ++c)
819 tmp.m[r*tmp.col+c] = this->m[r*col+c];
820 for (unsigned c=0; c<v.col; ++c)
821 tmp.m[r*tmp.col+c+col] = v.m[r*v.col+c];
823 // cout << "augmented: " << tmp << endl;
824 tmp.gauss_elimination();
825 // cout << "degaussed: " << tmp << endl;
826 // assemble the solution matrix
827 exvector sol(v.row*v.col);
828 for (unsigned c=0; c<v.col; ++c) {
829 for (unsigned r=row; r>0; --r) {
830 for (unsigned i=r; i<col; ++i)
831 sol[(r-1)*v.col+c] -= tmp.m[(r-1)*tmp.col+i]*sol[i*v.col+c];
832 sol[(r-1)*v.col+c] += tmp.m[(r-1)*tmp.col+col+c];
833 sol[(r-1)*v.col+c] = (sol[(r-1)*v.col+c]/tmp.m[(r-1)*tmp.col+(r-1)]).normal();
836 return matrix(v.row, v.col, sol);
842 /** Recursive determinant for small matrices having at least one symbolic
843 * entry. The basic algorithm, known as Laplace-expansion, is enhanced by
844 * some bookkeeping to avoid calculation of the same submatrices ("minors")
845 * more than once. According to W.M.Gentleman and S.C.Johnson this algorithm
846 * is better than elimination schemes for matrices of sparse multivariate
847 * polynomials and also for matrices of dense univariate polynomials if the
848 * matrix' dimesion is larger than 7.
850 * @return the determinant as a new expression (in expanded form)
851 * @see matrix::determinant() */
852 ex matrix::determinant_minor(void) const
854 // for small matrices the algorithm does not make any sense:
858 return (m[0]*m[3]-m[2]*m[1]).expand();
860 return (m[0]*m[4]*m[8]-m[0]*m[5]*m[7]-
861 m[1]*m[3]*m[8]+m[2]*m[3]*m[7]+
862 m[1]*m[5]*m[6]-m[2]*m[4]*m[6]).expand();
864 // This algorithm can best be understood by looking at a naive
865 // implementation of Laplace-expansion, like this one:
867 // matrix minorM(this->row-1,this->col-1);
868 // for (unsigned r1=0; r1<this->row; ++r1) {
869 // // shortcut if element(r1,0) vanishes
870 // if (m[r1*col].is_zero())
872 // // assemble the minor matrix
873 // for (unsigned r=0; r<minorM.rows(); ++r) {
874 // for (unsigned c=0; c<minorM.cols(); ++c) {
876 // minorM.set(r,c,m[r*col+c+1]);
878 // minorM.set(r,c,m[(r+1)*col+c+1]);
881 // // recurse down and care for sign:
883 // det -= m[r1*col] * minorM.determinant_minor();
885 // det += m[r1*col] * minorM.determinant_minor();
887 // return det.expand();
888 // What happens is that while proceeding down many of the minors are
889 // computed more than once. In particular, there are binomial(n,k)
890 // kxk minors and each one is computed factorial(n-k) times. Therefore
891 // it is reasonable to store the results of the minors. We proceed from
892 // right to left. At each column c we only need to retrieve the minors
893 // calculated in step c-1. We therefore only have to store at most
894 // 2*binomial(n,n/2) minors.
896 // Unique flipper counter for partitioning into minors
897 vector<unsigned> Pkey;
898 Pkey.reserve(this->col);
899 // key for minor determinant (a subpartition of Pkey)
900 vector<unsigned> Mkey;
901 Mkey.reserve(this->col-1);
902 // we store our subminors in maps, keys being the rows they arise from
903 typedef map<vector<unsigned>,class ex> Rmap;
904 typedef map<vector<unsigned>,class ex>::value_type Rmap_value;
908 // initialize A with last column:
909 for (unsigned r=0; r<this->col; ++r) {
910 Pkey.erase(Pkey.begin(),Pkey.end());
912 A.insert(Rmap_value(Pkey,m[this->col*r+this->col-1]));
914 // proceed from right to left through matrix
915 for (int c=this->col-2; c>=0; --c) {
916 Pkey.erase(Pkey.begin(),Pkey.end()); // don't change capacity
917 Mkey.erase(Mkey.begin(),Mkey.end());
918 for (unsigned i=0; i<this->col-c; ++i)
920 unsigned fc = 0; // controls logic for our strange flipper counter
923 for (unsigned r=0; r<this->col-c; ++r) {
924 // maybe there is nothing to do?
925 if (m[Pkey[r]*this->col+c].is_zero())
927 // create the sorted key for all possible minors
928 Mkey.erase(Mkey.begin(),Mkey.end());
929 for (unsigned i=0; i<this->col-c; ++i)
931 Mkey.push_back(Pkey[i]);
932 // Fetch the minors and compute the new determinant
934 det -= m[Pkey[r]*this->col+c]*A[Mkey];
936 det += m[Pkey[r]*this->col+c]*A[Mkey];
938 // prevent build-up of deep nesting of expressions saves time:
940 // store the new determinant at its place in B:
942 B.insert(Rmap_value(Pkey,det));
943 // increment our strange flipper counter
944 for (fc=this->col-c; fc>0; --fc) {
950 for (unsigned j=fc; j<this->col-c; ++j)
951 Pkey[j] = Pkey[j-1]+1;
953 // next column, so change the role of A and B:
962 /** Perform the steps of an ordinary Gaussian elimination to bring the matrix
963 * into an upper echelon form.
965 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
966 * number of rows was swapped and 0 if the matrix is singular. */
967 int matrix::gauss_elimination(void)
969 ensure_if_modifiable();
972 for (unsigned r1=0; r1<row-1; ++r1) {
973 int indx = pivot(r1);
975 return 0; // Note: leaves *this in a messy state.
978 for (unsigned r2=r1+1; r2<row; ++r2) {
979 piv = this->m[r2*col+r1] / this->m[r1*col+r1];
980 for (unsigned c=r1+1; c<col; ++c)
981 this->m[r2*col+c] -= piv * this->m[r1*col+c];
982 for (unsigned c=0; c<=r1; ++c)
983 this->m[r2*col+c] = _ex0();
991 /** Perform the steps of division free elimination to bring the matrix
992 * into an upper echelon form.
994 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
995 * number of rows was swapped and 0 if the matrix is singular. */
996 int matrix::division_free_elimination(void)
999 ensure_if_modifiable();
1000 for (unsigned r1=0; r1<row-1; ++r1) {
1001 int indx = pivot(r1);
1003 return 0; // Note: leaves *this in a messy state.
1006 for (unsigned r2=r1+1; r2<row; ++r2) {
1007 for (unsigned c=r1+1; c<col; ++c)
1008 this->m[r2*col+c] = this->m[r1*col+r1]*this->m[r2*col+c] - this->m[r2*col+r1]*this->m[r1*col+c];
1009 for (unsigned c=0; c<=r1; ++c)
1010 this->m[r2*col+c] = _ex0();
1018 /** Perform the steps of Bareiss' one-step fraction free elimination to bring
1019 * the matrix into an upper echelon form. Fraction free elimination means
1020 * that divide is used straightforwardly, without computing GCDs first. This
1021 * is possible, since we know the divisor at each step.
1023 * @param det may be set to true to save a lot of space if one is only
1024 * interested in the last element (i.e. for calculating determinants), the
1025 * others are set to zero in this case.
1026 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1027 * number of rows was swapped and 0 if the matrix is singular. */
1028 int matrix::fraction_free_elimination(bool det)
1031 // (single-step fraction free elimination scheme, already known to Jordan)
1033 // Usual division-free elimination sets m[0](r,c) = m(r,c) and then sets
1034 // m[k+1](r,c) = m[k](k,k) * m[k](r,c) - m[k](r,k) * m[k](k,c).
1036 // Bareiss (fraction-free) elimination in addition divides that element
1037 // by m[k-1](k-1,k-1) for k>1, where it can be shown by means of the
1038 // Sylvester determinant that this really divides m[k+1](r,c).
1040 // We also allow rational functions where the original prove still holds.
1041 // However, we must care for numerator and denominator separately and
1042 // "manually" work in the integral domains because of subtle cancellations
1043 // (see below). This blows up the bookkeeping a bit and the formula has
1044 // to be modified to expand like this (N{x} stands for numerator of x,
1045 // D{x} for denominator of x):
1046 // N{m[k+1](r,c)} = N{m[k](k,k)}*N{m[k](r,c)}*D{m[k](r,k)}*D{m[k](k,c)}
1047 // -N{m[k](r,k)}*N{m[k](k,c)}*D{m[k](k,k)}*D{m[k](r,c)}
1048 // D{m[k+1](r,c)} = D{m[k](k,k)}*D{m[k](r,c)}*D{m[k](r,k)}*D{m[k](k,c)}
1049 // where for k>1 we now divide N{m[k+1](r,c)} by
1050 // N{m[k-1](k-1,k-1)}
1051 // and D{m[k+1](r,c)} by
1052 // D{m[k-1](k-1,k-1)}.
1054 GINAC_ASSERT(det || row==col);
1055 ensure_if_modifiable();
1065 // We populate temporary matrices to subsequently operate on. There is
1066 // one holding numerators and another holding denominators of entries.
1067 // This is a must since the evaluator (or even earlier mul's constructor)
1068 // might cancel some trivial element which causes divide() to fail. The
1069 // elements are normalized first (yes, even though this algorithm doesn't
1070 // need GCDs) since the elements of *this might be unnormalized, which
1071 // makes things more complicated than they need to be.
1072 matrix tmp_n(*this);
1073 matrix tmp_d(row,col); // for denominators, if needed
1074 lst srl; // symbol replacement list
1075 exvector::iterator it = m.begin();
1076 exvector::iterator tmp_n_it = tmp_n.m.begin();
1077 exvector::iterator tmp_d_it = tmp_d.m.begin();
1078 for (; it!= m.end(); ++it, ++tmp_n_it, ++tmp_d_it) {
1079 (*tmp_n_it) = (*it).normal().to_rational(srl);
1080 (*tmp_d_it) = (*tmp_n_it).denom();
1081 (*tmp_n_it) = (*tmp_n_it).numer();
1084 for (unsigned r1=0; r1<row-1; ++r1) {
1085 int indx = tmp_n.pivot(r1);
1086 if (det && indx==-1)
1087 return 0; // FIXME: what to do if det is false, some day?
1090 // rows r1 and indx were swapped, so pivot matrix tmp_d:
1091 for (unsigned c=0; c<col; ++c)
1092 tmp_d.m[row*indx+c].swap(tmp_d.m[row*r1+c]);
1095 divisor_n = tmp_n.m[(r1-1)*col+(r1-1)].expand();
1096 divisor_d = tmp_d.m[(r1-1)*col+(r1-1)].expand();
1097 // save space by deleting no longer needed elements:
1099 for (unsigned c=0; c<col; ++c) {
1100 tmp_n.m[(r1-1)*col+c] = 0;
1101 tmp_d.m[(r1-1)*col+c] = 1;
1105 for (unsigned r2=r1+1; r2<row; ++r2) {
1106 for (unsigned c=r1+1; c<col; ++c) {
1107 dividend_n = (tmp_n.m[r1*col+r1]*tmp_n.m[r2*col+c]*
1108 tmp_d.m[r2*col+r1]*tmp_d.m[r1*col+c]
1109 -tmp_n.m[r2*col+r1]*tmp_n.m[r1*col+c]*
1110 tmp_d.m[r1*col+r1]*tmp_d.m[r2*col+c]).expand();
1111 dividend_d = (tmp_d.m[r2*col+r1]*tmp_d.m[r1*col+c]*
1112 tmp_d.m[r1*col+r1]*tmp_d.m[r2*col+c]).expand();
1113 bool check = divide(dividend_n, divisor_n,
1114 tmp_n.m[r2*col+c],true);
1115 check &= divide(dividend_d, divisor_d,
1116 tmp_d.m[r2*col+c],true);
1117 GINAC_ASSERT(check);
1119 // fill up left hand side.
1120 for (unsigned c=0; c<=r1; ++c)
1121 tmp_n.m[r2*col+c] = _ex0();
1124 // repopulate *this matrix:
1126 tmp_n_it = tmp_n.m.begin();
1127 tmp_d_it = tmp_d.m.begin();
1128 for (; it!= m.end(); ++it, ++tmp_n_it, ++tmp_d_it)
1129 (*it) = ((*tmp_n_it)/(*tmp_d_it)).subs(srl);
1135 /** Partial pivoting method for matrix elimination schemes.
1136 * Usual pivoting (symbolic==false) returns the index to the element with the
1137 * largest absolute value in column ro and swaps the current row with the one
1138 * where the element was found. With (symbolic==true) it does the same thing
1139 * with the first non-zero element.
1141 * @param ro is the row to be inspected
1142 * @param symbolic signal if we want the first non-zero element to be pivoted
1143 * (true) or the one with the largest absolute value (false).
1144 * @return 0 if no interchange occured, -1 if all are zero (usually signaling
1145 * a degeneracy) and positive integer k means that rows ro and k were swapped.
1147 int matrix::pivot(unsigned ro, bool symbolic)
1151 if (symbolic) { // search first non-zero
1152 for (unsigned r=ro; r<row; ++r) {
1153 if (!m[r*col+ro].is_zero()) {
1158 } else { // search largest
1161 for (unsigned r=ro; r<row; ++r) {
1162 GINAC_ASSERT(is_ex_of_type(m[r*col+ro],numeric));
1163 if ((tmp = abs(ex_to_numeric(m[r*col+ro]))) > maxn &&
1170 if (m[k*col+ro].is_zero())
1172 if (k!=ro) { // swap rows
1173 ensure_if_modifiable();
1174 for (unsigned c=0; c<col; ++c) {
1175 m[k*col+c].swap(m[ro*col+c]);
1182 /** Convert list of lists to matrix. */
1183 ex lst_to_matrix(const ex &l)
1185 if (!is_ex_of_type(l, lst))
1186 throw(std::invalid_argument("argument to lst_to_matrix() must be a lst"));
1188 // Find number of rows and columns
1189 unsigned rows = l.nops(), cols = 0, i, j;
1190 for (i=0; i<rows; i++)
1191 if (l.op(i).nops() > cols)
1192 cols = l.op(i).nops();
1194 // Allocate and fill matrix
1195 matrix &m = *new matrix(rows, cols);
1196 for (i=0; i<rows; i++)
1197 for (j=0; j<cols; j++)
1198 if (l.op(i).nops() > j)
1199 m.set(i, j, l.op(i).op(j));
1209 const matrix some_matrix;
1210 const type_info & typeid_matrix=typeid(some_matrix);
1212 #ifndef NO_NAMESPACE_GINAC
1213 } // namespace GiNaC
1214 #endif // ndef NO_NAMESPACE_GINAC