3 * Implementation of symbolic matrices */
6 * GiNaC Copyright (C) 1999-2005 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
38 #include "operators.h"
45 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(matrix, basic,
46 print_func<print_context>(&matrix::do_print).
47 print_func<print_latex>(&matrix::do_print_latex).
48 print_func<print_tree>(&matrix::do_print_tree).
49 print_func<print_python_repr>(&matrix::do_print_python_repr))
52 // default constructor
55 /** Default ctor. Initializes to 1 x 1-dimensional zero-matrix. */
56 matrix::matrix() : inherited(TINFO_matrix), row(1), col(1), m(1, _ex0)
58 setflag(status_flags::not_shareable);
67 /** Very common ctor. Initializes to r x c-dimensional zero-matrix.
69 * @param r number of rows
70 * @param c number of cols */
71 matrix::matrix(unsigned r, unsigned c)
72 : inherited(TINFO_matrix), row(r), col(c), m(r*c, _ex0)
74 setflag(status_flags::not_shareable);
79 /** Ctor from representation, for internal use only. */
80 matrix::matrix(unsigned r, unsigned c, const exvector & m2)
81 : inherited(TINFO_matrix), row(r), col(c), m(m2)
83 setflag(status_flags::not_shareable);
86 /** Construct matrix from (flat) list of elements. If the list has fewer
87 * elements than the matrix, the remaining matrix elements are set to zero.
88 * If the list has more elements than the matrix, the excessive elements are
90 matrix::matrix(unsigned r, unsigned c, const lst & l)
91 : inherited(TINFO_matrix), row(r), col(c), m(r*c, _ex0)
93 setflag(status_flags::not_shareable);
96 for (lst::const_iterator it = l.begin(); it != l.end(); ++it, ++i) {
100 break; // matrix smaller than list: throw away excessive elements
109 matrix::matrix(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
111 setflag(status_flags::not_shareable);
113 if (!(n.find_unsigned("row", row)) || !(n.find_unsigned("col", col)))
114 throw (std::runtime_error("unknown matrix dimensions in archive"));
115 m.reserve(row * col);
116 for (unsigned int i=0; true; i++) {
118 if (n.find_ex("m", e, sym_lst, i))
125 void matrix::archive(archive_node &n) const
127 inherited::archive(n);
128 n.add_unsigned("row", row);
129 n.add_unsigned("col", col);
130 exvector::const_iterator i = m.begin(), iend = m.end();
137 DEFAULT_UNARCHIVE(matrix)
140 // functions overriding virtual functions from base classes
145 void matrix::print_elements(const print_context & c, const char *row_start, const char *row_end, const char *row_sep, const char *col_sep) const
147 for (unsigned ro=0; ro<row; ++ro) {
149 for (unsigned co=0; co<col; ++co) {
150 m[ro*col+co].print(c);
161 void matrix::do_print(const print_context & c, unsigned level) const
164 print_elements(c, "[", "]", ",", ",");
168 void matrix::do_print_latex(const print_latex & c, unsigned level) const
170 c.s << "\\left(\\begin{array}{" << std::string(col,'c') << "}";
171 print_elements(c, "", "", "\\\\", "&");
172 c.s << "\\end{array}\\right)";
175 void matrix::do_print_python_repr(const print_python_repr & c, unsigned level) const
177 c.s << class_name() << '(';
178 print_elements(c, "[", "]", ",", ",");
182 /** nops is defined to be rows x columns. */
183 size_t matrix::nops() const
185 return static_cast<size_t>(row) * static_cast<size_t>(col);
188 /** returns matrix entry at position (i/col, i%col). */
189 ex matrix::op(size_t i) const
191 GINAC_ASSERT(i<nops());
196 /** returns writable matrix entry at position (i/col, i%col). */
197 ex & matrix::let_op(size_t i)
199 GINAC_ASSERT(i<nops());
201 ensure_if_modifiable();
205 /** Evaluate matrix entry by entry. */
206 ex matrix::eval(int level) const
208 // check if we have to do anything at all
209 if ((level==1)&&(flags & status_flags::evaluated))
213 if (level == -max_recursion_level)
214 throw (std::runtime_error("matrix::eval(): recursion limit exceeded"));
216 // eval() entry by entry
217 exvector m2(row*col);
219 for (unsigned r=0; r<row; ++r)
220 for (unsigned c=0; c<col; ++c)
221 m2[r*col+c] = m[r*col+c].eval(level);
223 return (new matrix(row, col, m2))->setflag(status_flags::dynallocated |
224 status_flags::evaluated);
227 ex matrix::subs(const exmap & mp, unsigned options) const
229 exvector m2(row * col);
230 for (unsigned r=0; r<row; ++r)
231 for (unsigned c=0; c<col; ++c)
232 m2[r*col+c] = m[r*col+c].subs(mp, options);
234 return matrix(row, col, m2).subs_one_level(mp, options);
237 /** Complex conjugate every matrix entry. */
238 ex matrix::conjugate() const
241 for (exvector::const_iterator i=m.begin(); i!=m.end(); ++i) {
242 ex x = i->conjugate();
247 if (are_ex_trivially_equal(x, *i)) {
251 ev->reserve(m.size());
252 for (exvector::const_iterator j=m.begin(); j!=i; ++j) {
258 ex result = matrix(row, col, *ev);
267 int matrix::compare_same_type(const basic & other) const
269 GINAC_ASSERT(is_exactly_a<matrix>(other));
270 const matrix &o = static_cast<const matrix &>(other);
272 // compare number of rows
274 return row < o.rows() ? -1 : 1;
276 // compare number of columns
278 return col < o.cols() ? -1 : 1;
280 // equal number of rows and columns, compare individual elements
282 for (unsigned r=0; r<row; ++r) {
283 for (unsigned c=0; c<col; ++c) {
284 cmpval = ((*this)(r,c)).compare(o(r,c));
285 if (cmpval!=0) return cmpval;
288 // all elements are equal => matrices are equal;
292 bool matrix::match_same_type(const basic & other) const
294 GINAC_ASSERT(is_exactly_a<matrix>(other));
295 const matrix & o = static_cast<const matrix &>(other);
297 // The number of rows and columns must be the same. This is necessary to
298 // prevent a 2x3 matrix from matching a 3x2 one.
299 return row == o.rows() && col == o.cols();
302 /** Automatic symbolic evaluation of an indexed matrix. */
303 ex matrix::eval_indexed(const basic & i) const
305 GINAC_ASSERT(is_a<indexed>(i));
306 GINAC_ASSERT(is_a<matrix>(i.op(0)));
308 bool all_indices_unsigned = static_cast<const indexed &>(i).all_index_values_are(info_flags::nonnegint);
313 // One index, must be one-dimensional vector
314 if (row != 1 && col != 1)
315 throw (std::runtime_error("matrix::eval_indexed(): vector must have exactly 1 index"));
317 const idx & i1 = ex_to<idx>(i.op(1));
322 if (!i1.get_dim().is_equal(row))
323 throw (std::runtime_error("matrix::eval_indexed(): dimension of index must match number of vector elements"));
325 // Index numeric -> return vector element
326 if (all_indices_unsigned) {
327 unsigned n1 = ex_to<numeric>(i1.get_value()).to_int();
329 throw (std::runtime_error("matrix::eval_indexed(): value of index exceeds number of vector elements"));
330 return (*this)(n1, 0);
336 if (!i1.get_dim().is_equal(col))
337 throw (std::runtime_error("matrix::eval_indexed(): dimension of index must match number of vector elements"));
339 // Index numeric -> return vector element
340 if (all_indices_unsigned) {
341 unsigned n1 = ex_to<numeric>(i1.get_value()).to_int();
343 throw (std::runtime_error("matrix::eval_indexed(): value of index exceeds number of vector elements"));
344 return (*this)(0, n1);
348 } else if (i.nops() == 3) {
351 const idx & i1 = ex_to<idx>(i.op(1));
352 const idx & i2 = ex_to<idx>(i.op(2));
354 if (!i1.get_dim().is_equal(row))
355 throw (std::runtime_error("matrix::eval_indexed(): dimension of first index must match number of rows"));
356 if (!i2.get_dim().is_equal(col))
357 throw (std::runtime_error("matrix::eval_indexed(): dimension of second index must match number of columns"));
359 // Pair of dummy indices -> compute trace
360 if (is_dummy_pair(i1, i2))
363 // Both indices numeric -> return matrix element
364 if (all_indices_unsigned) {
365 unsigned n1 = ex_to<numeric>(i1.get_value()).to_int(), n2 = ex_to<numeric>(i2.get_value()).to_int();
367 throw (std::runtime_error("matrix::eval_indexed(): value of first index exceeds number of rows"));
369 throw (std::runtime_error("matrix::eval_indexed(): value of second index exceeds number of columns"));
370 return (*this)(n1, n2);
374 throw (std::runtime_error("matrix::eval_indexed(): matrix must have exactly 2 indices"));
379 /** Sum of two indexed matrices. */
380 ex matrix::add_indexed(const ex & self, const ex & other) const
382 GINAC_ASSERT(is_a<indexed>(self));
383 GINAC_ASSERT(is_a<matrix>(self.op(0)));
384 GINAC_ASSERT(is_a<indexed>(other));
385 GINAC_ASSERT(self.nops() == 2 || self.nops() == 3);
387 // Only add two matrices
388 if (is_a<matrix>(other.op(0))) {
389 GINAC_ASSERT(other.nops() == 2 || other.nops() == 3);
391 const matrix &self_matrix = ex_to<matrix>(self.op(0));
392 const matrix &other_matrix = ex_to<matrix>(other.op(0));
394 if (self.nops() == 2 && other.nops() == 2) { // vector + vector
396 if (self_matrix.row == other_matrix.row)
397 return indexed(self_matrix.add(other_matrix), self.op(1));
398 else if (self_matrix.row == other_matrix.col)
399 return indexed(self_matrix.add(other_matrix.transpose()), self.op(1));
401 } else if (self.nops() == 3 && other.nops() == 3) { // matrix + matrix
403 if (self.op(1).is_equal(other.op(1)) && self.op(2).is_equal(other.op(2)))
404 return indexed(self_matrix.add(other_matrix), self.op(1), self.op(2));
405 else if (self.op(1).is_equal(other.op(2)) && self.op(2).is_equal(other.op(1)))
406 return indexed(self_matrix.add(other_matrix.transpose()), self.op(1), self.op(2));
411 // Don't know what to do, return unevaluated sum
415 /** Product of an indexed matrix with a number. */
416 ex matrix::scalar_mul_indexed(const ex & self, const numeric & other) const
418 GINAC_ASSERT(is_a<indexed>(self));
419 GINAC_ASSERT(is_a<matrix>(self.op(0)));
420 GINAC_ASSERT(self.nops() == 2 || self.nops() == 3);
422 const matrix &self_matrix = ex_to<matrix>(self.op(0));
424 if (self.nops() == 2)
425 return indexed(self_matrix.mul(other), self.op(1));
426 else // self.nops() == 3
427 return indexed(self_matrix.mul(other), self.op(1), self.op(2));
430 /** Contraction of an indexed matrix with something else. */
431 bool matrix::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
433 GINAC_ASSERT(is_a<indexed>(*self));
434 GINAC_ASSERT(is_a<indexed>(*other));
435 GINAC_ASSERT(self->nops() == 2 || self->nops() == 3);
436 GINAC_ASSERT(is_a<matrix>(self->op(0)));
438 // Only contract with other matrices
439 if (!is_a<matrix>(other->op(0)))
442 GINAC_ASSERT(other->nops() == 2 || other->nops() == 3);
444 const matrix &self_matrix = ex_to<matrix>(self->op(0));
445 const matrix &other_matrix = ex_to<matrix>(other->op(0));
447 if (self->nops() == 2) {
449 if (other->nops() == 2) { // vector * vector (scalar product)
451 if (self_matrix.col == 1) {
452 if (other_matrix.col == 1) {
453 // Column vector * column vector, transpose first vector
454 *self = self_matrix.transpose().mul(other_matrix)(0, 0);
456 // Column vector * row vector, swap factors
457 *self = other_matrix.mul(self_matrix)(0, 0);
460 if (other_matrix.col == 1) {
461 // Row vector * column vector, perfect
462 *self = self_matrix.mul(other_matrix)(0, 0);
464 // Row vector * row vector, transpose second vector
465 *self = self_matrix.mul(other_matrix.transpose())(0, 0);
471 } else { // vector * matrix
473 // B_i * A_ij = (B*A)_j (B is row vector)
474 if (is_dummy_pair(self->op(1), other->op(1))) {
475 if (self_matrix.row == 1)
476 *self = indexed(self_matrix.mul(other_matrix), other->op(2));
478 *self = indexed(self_matrix.transpose().mul(other_matrix), other->op(2));
483 // B_j * A_ij = (A*B)_i (B is column vector)
484 if (is_dummy_pair(self->op(1), other->op(2))) {
485 if (self_matrix.col == 1)
486 *self = indexed(other_matrix.mul(self_matrix), other->op(1));
488 *self = indexed(other_matrix.mul(self_matrix.transpose()), other->op(1));
494 } else if (other->nops() == 3) { // matrix * matrix
496 // A_ij * B_jk = (A*B)_ik
497 if (is_dummy_pair(self->op(2), other->op(1))) {
498 *self = indexed(self_matrix.mul(other_matrix), self->op(1), other->op(2));
503 // A_ij * B_kj = (A*Btrans)_ik
504 if (is_dummy_pair(self->op(2), other->op(2))) {
505 *self = indexed(self_matrix.mul(other_matrix.transpose()), self->op(1), other->op(1));
510 // A_ji * B_jk = (Atrans*B)_ik
511 if (is_dummy_pair(self->op(1), other->op(1))) {
512 *self = indexed(self_matrix.transpose().mul(other_matrix), self->op(2), other->op(2));
517 // A_ji * B_kj = (B*A)_ki
518 if (is_dummy_pair(self->op(1), other->op(2))) {
519 *self = indexed(other_matrix.mul(self_matrix), other->op(1), self->op(2));
530 // non-virtual functions in this class
537 * @exception logic_error (incompatible matrices) */
538 matrix matrix::add(const matrix & other) const
540 if (col != other.col || row != other.row)
541 throw std::logic_error("matrix::add(): incompatible matrices");
543 exvector sum(this->m);
544 exvector::iterator i = sum.begin(), end = sum.end();
545 exvector::const_iterator ci = other.m.begin();
549 return matrix(row,col,sum);
553 /** Difference of matrices.
555 * @exception logic_error (incompatible matrices) */
556 matrix matrix::sub(const matrix & other) const
558 if (col != other.col || row != other.row)
559 throw std::logic_error("matrix::sub(): incompatible matrices");
561 exvector dif(this->m);
562 exvector::iterator i = dif.begin(), end = dif.end();
563 exvector::const_iterator ci = other.m.begin();
567 return matrix(row,col,dif);
571 /** Product of matrices.
573 * @exception logic_error (incompatible matrices) */
574 matrix matrix::mul(const matrix & other) const
576 if (this->cols() != other.rows())
577 throw std::logic_error("matrix::mul(): incompatible matrices");
579 exvector prod(this->rows()*other.cols());
581 for (unsigned r1=0; r1<this->rows(); ++r1) {
582 for (unsigned c=0; c<this->cols(); ++c) {
583 if (m[r1*col+c].is_zero())
585 for (unsigned r2=0; r2<other.cols(); ++r2)
586 prod[r1*other.col+r2] += (m[r1*col+c] * other.m[c*other.col+r2]).expand();
589 return matrix(row, other.col, prod);
593 /** Product of matrix and scalar. */
594 matrix matrix::mul(const numeric & other) const
596 exvector prod(row * col);
598 for (unsigned r=0; r<row; ++r)
599 for (unsigned c=0; c<col; ++c)
600 prod[r*col+c] = m[r*col+c] * other;
602 return matrix(row, col, prod);
606 /** Product of matrix and scalar expression. */
607 matrix matrix::mul_scalar(const ex & other) const
609 if (other.return_type() != return_types::commutative)
610 throw std::runtime_error("matrix::mul_scalar(): non-commutative scalar");
612 exvector prod(row * col);
614 for (unsigned r=0; r<row; ++r)
615 for (unsigned c=0; c<col; ++c)
616 prod[r*col+c] = m[r*col+c] * other;
618 return matrix(row, col, prod);
622 /** Power of a matrix. Currently handles integer exponents only. */
623 matrix matrix::pow(const ex & expn) const
626 throw (std::logic_error("matrix::pow(): matrix not square"));
628 if (is_exactly_a<numeric>(expn)) {
629 // Integer cases are computed by successive multiplication, using the
630 // obvious shortcut of storing temporaries, like A^4 == (A*A)*(A*A).
631 if (expn.info(info_flags::integer)) {
632 numeric b = ex_to<numeric>(expn);
634 if (expn.info(info_flags::negative)) {
641 for (unsigned r=0; r<row; ++r)
645 // This loop computes the representation of b in base 2 from right
646 // to left and multiplies the factors whenever needed. Note
647 // that this is not entirely optimal but close to optimal and
648 // "better" algorithms are much harder to implement. (See Knuth,
649 // TAoCP2, section "Evaluation of Powers" for a good discussion.)
650 while (b!=*_num1_p) {
655 b /= *_num2_p; // still integer.
661 throw (std::runtime_error("matrix::pow(): don't know how to handle exponent"));
665 /** operator() to access elements for reading.
667 * @param ro row of element
668 * @param co column of element
669 * @exception range_error (index out of range) */
670 const ex & matrix::operator() (unsigned ro, unsigned co) const
672 if (ro>=row || co>=col)
673 throw (std::range_error("matrix::operator(): index out of range"));
679 /** operator() to access elements for writing.
681 * @param ro row of element
682 * @param co column of element
683 * @exception range_error (index out of range) */
684 ex & matrix::operator() (unsigned ro, unsigned co)
686 if (ro>=row || co>=col)
687 throw (std::range_error("matrix::operator(): index out of range"));
689 ensure_if_modifiable();
694 /** Transposed of an m x n matrix, producing a new n x m matrix object that
695 * represents the transposed. */
696 matrix matrix::transpose() const
698 exvector trans(this->cols()*this->rows());
700 for (unsigned r=0; r<this->cols(); ++r)
701 for (unsigned c=0; c<this->rows(); ++c)
702 trans[r*this->rows()+c] = m[c*this->cols()+r];
704 return matrix(this->cols(),this->rows(),trans);
707 /** Determinant of square matrix. This routine doesn't actually calculate the
708 * determinant, it only implements some heuristics about which algorithm to
709 * run. If all the elements of the matrix are elements of an integral domain
710 * the determinant is also in that integral domain and the result is expanded
711 * only. If one or more elements are from a quotient field the determinant is
712 * usually also in that quotient field and the result is normalized before it
713 * is returned. This implies that the determinant of the symbolic 2x2 matrix
714 * [[a/(a-b),1],[b/(a-b),1]] is returned as unity. (In this respect, it
715 * behaves like MapleV and unlike Mathematica.)
717 * @param algo allows to chose an algorithm
718 * @return the determinant as a new expression
719 * @exception logic_error (matrix not square)
720 * @see determinant_algo */
721 ex matrix::determinant(unsigned algo) const
724 throw (std::logic_error("matrix::determinant(): matrix not square"));
725 GINAC_ASSERT(row*col==m.capacity());
727 // Gather some statistical information about this matrix:
728 bool numeric_flag = true;
729 bool normal_flag = false;
730 unsigned sparse_count = 0; // counts non-zero elements
731 exvector::const_iterator r = m.begin(), rend = m.end();
733 if (!r->info(info_flags::numeric))
734 numeric_flag = false;
735 exmap srl; // symbol replacement list
736 ex rtest = r->to_rational(srl);
737 if (!rtest.is_zero())
739 if (!rtest.info(info_flags::crational_polynomial) &&
740 rtest.info(info_flags::rational_function))
745 // Here is the heuristics in case this routine has to decide:
746 if (algo == determinant_algo::automatic) {
747 // Minor expansion is generally a good guess:
748 algo = determinant_algo::laplace;
749 // Does anybody know when a matrix is really sparse?
750 // Maybe <~row/2.236 nonzero elements average in a row?
751 if (row>3 && 5*sparse_count<=row*col)
752 algo = determinant_algo::bareiss;
753 // Purely numeric matrix can be handled by Gauss elimination.
754 // This overrides any prior decisions.
756 algo = determinant_algo::gauss;
759 // Trap the trivial case here, since some algorithms don't like it
761 // for consistency with non-trivial determinants...
763 return m[0].normal();
765 return m[0].expand();
768 // Compute the determinant
770 case determinant_algo::gauss: {
773 int sign = tmp.gauss_elimination(true);
774 for (unsigned d=0; d<row; ++d)
775 det *= tmp.m[d*col+d];
777 return (sign*det).normal();
779 return (sign*det).normal().expand();
781 case determinant_algo::bareiss: {
784 sign = tmp.fraction_free_elimination(true);
786 return (sign*tmp.m[row*col-1]).normal();
788 return (sign*tmp.m[row*col-1]).expand();
790 case determinant_algo::divfree: {
793 sign = tmp.division_free_elimination(true);
796 ex det = tmp.m[row*col-1];
797 // factor out accumulated bogus slag
798 for (unsigned d=0; d<row-2; ++d)
799 for (unsigned j=0; j<row-d-2; ++j)
800 det = (det/tmp.m[d*col+d]).normal();
803 case determinant_algo::laplace:
805 // This is the minor expansion scheme. We always develop such
806 // that the smallest minors (i.e, the trivial 1x1 ones) are on the
807 // rightmost column. For this to be efficient, empirical tests
808 // have shown that the emptiest columns (i.e. the ones with most
809 // zeros) should be the ones on the right hand side -- although
810 // this might seem counter-intuitive (and in contradiction to some
811 // literature like the FORM manual). Please go ahead and test it
812 // if you don't believe me! Therefore we presort the columns of
814 typedef std::pair<unsigned,unsigned> uintpair;
815 std::vector<uintpair> c_zeros; // number of zeros in column
816 for (unsigned c=0; c<col; ++c) {
818 for (unsigned r=0; r<row; ++r)
819 if (m[r*col+c].is_zero())
821 c_zeros.push_back(uintpair(acc,c));
823 std::sort(c_zeros.begin(),c_zeros.end());
824 std::vector<unsigned> pre_sort;
825 for (std::vector<uintpair>::const_iterator i=c_zeros.begin(); i!=c_zeros.end(); ++i)
826 pre_sort.push_back(i->second);
827 std::vector<unsigned> pre_sort_test(pre_sort); // permutation_sign() modifies the vector so we make a copy here
828 int sign = permutation_sign(pre_sort_test.begin(), pre_sort_test.end());
829 exvector result(row*col); // represents sorted matrix
831 for (std::vector<unsigned>::const_iterator i=pre_sort.begin();
834 for (unsigned r=0; r<row; ++r)
835 result[r*col+c] = m[r*col+(*i)];
839 return (sign*matrix(row,col,result).determinant_minor()).normal();
841 return sign*matrix(row,col,result).determinant_minor();
847 /** Trace of a matrix. The result is normalized if it is in some quotient
848 * field and expanded only otherwise. This implies that the trace of the
849 * symbolic 2x2 matrix [[a/(a-b),x],[y,b/(b-a)]] is recognized to be unity.
851 * @return the sum of diagonal elements
852 * @exception logic_error (matrix not square) */
853 ex matrix::trace() const
856 throw (std::logic_error("matrix::trace(): matrix not square"));
859 for (unsigned r=0; r<col; ++r)
862 if (tr.info(info_flags::rational_function) &&
863 !tr.info(info_flags::crational_polynomial))
870 /** Characteristic Polynomial. Following mathematica notation the
871 * characteristic polynomial of a matrix M is defined as the determiant of
872 * (M - lambda * 1) where 1 stands for the unit matrix of the same dimension
873 * as M. Note that some CASs define it with a sign inside the determinant
874 * which gives rise to an overall sign if the dimension is odd. This method
875 * returns the characteristic polynomial collected in powers of lambda as a
878 * @return characteristic polynomial as new expression
879 * @exception logic_error (matrix not square)
880 * @see matrix::determinant() */
881 ex matrix::charpoly(const ex & lambda) const
884 throw (std::logic_error("matrix::charpoly(): matrix not square"));
886 bool numeric_flag = true;
887 exvector::const_iterator r = m.begin(), rend = m.end();
888 while (r!=rend && numeric_flag==true) {
889 if (!r->info(info_flags::numeric))
890 numeric_flag = false;
894 // The pure numeric case is traditionally rather common. Hence, it is
895 // trapped and we use Leverrier's algorithm which goes as row^3 for
896 // every coefficient. The expensive part is the matrix multiplication.
901 ex poly = power(lambda, row) - c*power(lambda, row-1);
902 for (unsigned i=1; i<row; ++i) {
903 for (unsigned j=0; j<row; ++j)
906 c = B.trace() / ex(i+1);
907 poly -= c*power(lambda, row-i-1);
917 for (unsigned r=0; r<col; ++r)
918 M.m[r*col+r] -= lambda;
920 return M.determinant().collect(lambda);
925 /** Inverse of this matrix.
927 * @return the inverted matrix
928 * @exception logic_error (matrix not square)
929 * @exception runtime_error (singular matrix) */
930 matrix matrix::inverse() const
933 throw (std::logic_error("matrix::inverse(): matrix not square"));
935 // This routine actually doesn't do anything fancy at all. We compute the
936 // inverse of the matrix A by solving the system A * A^{-1} == Id.
938 // First populate the identity matrix supposed to become the right hand side.
939 matrix identity(row,col);
940 for (unsigned i=0; i<row; ++i)
941 identity(i,i) = _ex1;
943 // Populate a dummy matrix of variables, just because of compatibility with
944 // matrix::solve() which wants this (for compatibility with under-determined
945 // systems of equations).
946 matrix vars(row,col);
947 for (unsigned r=0; r<row; ++r)
948 for (unsigned c=0; c<col; ++c)
949 vars(r,c) = symbol();
953 sol = this->solve(vars,identity);
954 } catch (const std::runtime_error & e) {
955 if (e.what()==std::string("matrix::solve(): inconsistent linear system"))
956 throw (std::runtime_error("matrix::inverse(): singular matrix"));
964 /** Solve a linear system consisting of a m x n matrix and a m x p right hand
965 * side by applying an elimination scheme to the augmented matrix.
967 * @param vars n x p matrix, all elements must be symbols
968 * @param rhs m x p matrix
969 * @param algo selects the solving algorithm
970 * @return n x p solution matrix
971 * @exception logic_error (incompatible matrices)
972 * @exception invalid_argument (1st argument must be matrix of symbols)
973 * @exception runtime_error (inconsistent linear system)
975 matrix matrix::solve(const matrix & vars,
979 const unsigned m = this->rows();
980 const unsigned n = this->cols();
981 const unsigned p = rhs.cols();
984 if ((rhs.rows() != m) || (vars.rows() != n) || (vars.col != p))
985 throw (std::logic_error("matrix::solve(): incompatible matrices"));
986 for (unsigned ro=0; ro<n; ++ro)
987 for (unsigned co=0; co<p; ++co)
988 if (!vars(ro,co).info(info_flags::symbol))
989 throw (std::invalid_argument("matrix::solve(): 1st argument must be matrix of symbols"));
991 // build the augmented matrix of *this with rhs attached to the right
993 for (unsigned r=0; r<m; ++r) {
994 for (unsigned c=0; c<n; ++c)
995 aug.m[r*(n+p)+c] = this->m[r*n+c];
996 for (unsigned c=0; c<p; ++c)
997 aug.m[r*(n+p)+c+n] = rhs.m[r*p+c];
1000 // Gather some statistical information about the augmented matrix:
1001 bool numeric_flag = true;
1002 exvector::const_iterator r = aug.m.begin(), rend = aug.m.end();
1003 while (r!=rend && numeric_flag==true) {
1004 if (!r->info(info_flags::numeric))
1005 numeric_flag = false;
1009 // Here is the heuristics in case this routine has to decide:
1010 if (algo == solve_algo::automatic) {
1011 // Bareiss (fraction-free) elimination is generally a good guess:
1012 algo = solve_algo::bareiss;
1013 // For m<3, Bareiss elimination is equivalent to division free
1014 // elimination but has more logistic overhead
1016 algo = solve_algo::divfree;
1017 // This overrides any prior decisions.
1019 algo = solve_algo::gauss;
1022 // Eliminate the augmented matrix:
1024 case solve_algo::gauss:
1025 aug.gauss_elimination();
1027 case solve_algo::divfree:
1028 aug.division_free_elimination();
1030 case solve_algo::bareiss:
1032 aug.fraction_free_elimination();
1035 // assemble the solution matrix:
1037 for (unsigned co=0; co<p; ++co) {
1038 unsigned last_assigned_sol = n+1;
1039 for (int r=m-1; r>=0; --r) {
1040 unsigned fnz = 1; // first non-zero in row
1041 while ((fnz<=n) && (aug.m[r*(n+p)+(fnz-1)].is_zero()))
1044 // row consists only of zeros, corresponding rhs must be 0, too
1045 if (!aug.m[r*(n+p)+n+co].is_zero()) {
1046 throw (std::runtime_error("matrix::solve(): inconsistent linear system"));
1049 // assign solutions for vars between fnz+1 and
1050 // last_assigned_sol-1: free parameters
1051 for (unsigned c=fnz; c<last_assigned_sol-1; ++c)
1052 sol(c,co) = vars.m[c*p+co];
1053 ex e = aug.m[r*(n+p)+n+co];
1054 for (unsigned c=fnz; c<n; ++c)
1055 e -= aug.m[r*(n+p)+c]*sol.m[c*p+co];
1056 sol(fnz-1,co) = (e/(aug.m[r*(n+p)+(fnz-1)])).normal();
1057 last_assigned_sol = fnz;
1060 // assign solutions for vars between 1 and
1061 // last_assigned_sol-1: free parameters
1062 for (unsigned ro=0; ro<last_assigned_sol-1; ++ro)
1063 sol(ro,co) = vars(ro,co);
1070 /** Compute the rank of this matrix. */
1071 unsigned matrix::rank() const
1074 // Transform this matrix into upper echelon form and then count the
1075 // number of non-zero rows.
1077 GINAC_ASSERT(row*col==m.capacity());
1079 // Actually, any elimination scheme will do since we are only
1080 // interested in the echelon matrix' zeros.
1081 matrix to_eliminate = *this;
1082 to_eliminate.fraction_free_elimination();
1084 unsigned r = row*col; // index of last non-zero element
1086 if (!to_eliminate.m[r].is_zero())
1095 /** Recursive determinant for small matrices having at least one symbolic
1096 * entry. The basic algorithm, known as Laplace-expansion, is enhanced by
1097 * some bookkeeping to avoid calculation of the same submatrices ("minors")
1098 * more than once. According to W.M.Gentleman and S.C.Johnson this algorithm
1099 * is better than elimination schemes for matrices of sparse multivariate
1100 * polynomials and also for matrices of dense univariate polynomials if the
1101 * matrix' dimesion is larger than 7.
1103 * @return the determinant as a new expression (in expanded form)
1104 * @see matrix::determinant() */
1105 ex matrix::determinant_minor() const
1107 // for small matrices the algorithm does not make any sense:
1108 const unsigned n = this->cols();
1110 return m[0].expand();
1112 return (m[0]*m[3]-m[2]*m[1]).expand();
1114 return (m[0]*m[4]*m[8]-m[0]*m[5]*m[7]-
1115 m[1]*m[3]*m[8]+m[2]*m[3]*m[7]+
1116 m[1]*m[5]*m[6]-m[2]*m[4]*m[6]).expand();
1118 // This algorithm can best be understood by looking at a naive
1119 // implementation of Laplace-expansion, like this one:
1121 // matrix minorM(this->rows()-1,this->cols()-1);
1122 // for (unsigned r1=0; r1<this->rows(); ++r1) {
1123 // // shortcut if element(r1,0) vanishes
1124 // if (m[r1*col].is_zero())
1126 // // assemble the minor matrix
1127 // for (unsigned r=0; r<minorM.rows(); ++r) {
1128 // for (unsigned c=0; c<minorM.cols(); ++c) {
1130 // minorM(r,c) = m[r*col+c+1];
1132 // minorM(r,c) = m[(r+1)*col+c+1];
1135 // // recurse down and care for sign:
1137 // det -= m[r1*col] * minorM.determinant_minor();
1139 // det += m[r1*col] * minorM.determinant_minor();
1141 // return det.expand();
1142 // What happens is that while proceeding down many of the minors are
1143 // computed more than once. In particular, there are binomial(n,k)
1144 // kxk minors and each one is computed factorial(n-k) times. Therefore
1145 // it is reasonable to store the results of the minors. We proceed from
1146 // right to left. At each column c we only need to retrieve the minors
1147 // calculated in step c-1. We therefore only have to store at most
1148 // 2*binomial(n,n/2) minors.
1150 // Unique flipper counter for partitioning into minors
1151 std::vector<unsigned> Pkey;
1153 // key for minor determinant (a subpartition of Pkey)
1154 std::vector<unsigned> Mkey;
1156 // we store our subminors in maps, keys being the rows they arise from
1157 typedef std::map<std::vector<unsigned>,class ex> Rmap;
1158 typedef std::map<std::vector<unsigned>,class ex>::value_type Rmap_value;
1162 // initialize A with last column:
1163 for (unsigned r=0; r<n; ++r) {
1164 Pkey.erase(Pkey.begin(),Pkey.end());
1166 A.insert(Rmap_value(Pkey,m[n*(r+1)-1]));
1168 // proceed from right to left through matrix
1169 for (int c=n-2; c>=0; --c) {
1170 Pkey.erase(Pkey.begin(),Pkey.end()); // don't change capacity
1171 Mkey.erase(Mkey.begin(),Mkey.end());
1172 for (unsigned i=0; i<n-c; ++i)
1174 unsigned fc = 0; // controls logic for our strange flipper counter
1177 for (unsigned r=0; r<n-c; ++r) {
1178 // maybe there is nothing to do?
1179 if (m[Pkey[r]*n+c].is_zero())
1181 // create the sorted key for all possible minors
1182 Mkey.erase(Mkey.begin(),Mkey.end());
1183 for (unsigned i=0; i<n-c; ++i)
1185 Mkey.push_back(Pkey[i]);
1186 // Fetch the minors and compute the new determinant
1188 det -= m[Pkey[r]*n+c]*A[Mkey];
1190 det += m[Pkey[r]*n+c]*A[Mkey];
1192 // prevent build-up of deep nesting of expressions saves time:
1194 // store the new determinant at its place in B:
1196 B.insert(Rmap_value(Pkey,det));
1197 // increment our strange flipper counter
1198 for (fc=n-c; fc>0; --fc) {
1200 if (Pkey[fc-1]<fc+c)
1204 for (unsigned j=fc; j<n-c; ++j)
1205 Pkey[j] = Pkey[j-1]+1;
1207 // next column, so change the role of A and B:
1216 /** Perform the steps of an ordinary Gaussian elimination to bring the m x n
1217 * matrix into an upper echelon form. The algorithm is ok for matrices
1218 * with numeric coefficients but quite unsuited for symbolic matrices.
1220 * @param det may be set to true to save a lot of space if one is only
1221 * interested in the diagonal elements (i.e. for calculating determinants).
1222 * The others are set to zero in this case.
1223 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1224 * number of rows was swapped and 0 if the matrix is singular. */
1225 int matrix::gauss_elimination(const bool det)
1227 ensure_if_modifiable();
1228 const unsigned m = this->rows();
1229 const unsigned n = this->cols();
1230 GINAC_ASSERT(!det || n==m);
1234 for (unsigned c0=0; c0<n && r0<m-1; ++c0) {
1235 int indx = pivot(r0, c0, true);
1239 return 0; // leaves *this in a messy state
1244 for (unsigned r2=r0+1; r2<m; ++r2) {
1245 if (!this->m[r2*n+c0].is_zero()) {
1246 // yes, there is something to do in this row
1247 ex piv = this->m[r2*n+c0] / this->m[r0*n+c0];
1248 for (unsigned c=c0+1; c<n; ++c) {
1249 this->m[r2*n+c] -= piv * this->m[r0*n+c];
1250 if (!this->m[r2*n+c].info(info_flags::numeric))
1251 this->m[r2*n+c] = this->m[r2*n+c].normal();
1254 // fill up left hand side with zeros
1255 for (unsigned c=r0; c<=c0; ++c)
1256 this->m[r2*n+c] = _ex0;
1259 // save space by deleting no longer needed elements
1260 for (unsigned c=r0+1; c<n; ++c)
1261 this->m[r0*n+c] = _ex0;
1266 // clear remaining rows
1267 for (unsigned r=r0+1; r<m; ++r) {
1268 for (unsigned c=0; c<n; ++c)
1269 this->m[r*n+c] = _ex0;
1276 /** Perform the steps of division free elimination to bring the m x n matrix
1277 * into an upper echelon form.
1279 * @param det may be set to true to save a lot of space if one is only
1280 * interested in the diagonal elements (i.e. for calculating determinants).
1281 * The others are set to zero in this case.
1282 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1283 * number of rows was swapped and 0 if the matrix is singular. */
1284 int matrix::division_free_elimination(const bool det)
1286 ensure_if_modifiable();
1287 const unsigned m = this->rows();
1288 const unsigned n = this->cols();
1289 GINAC_ASSERT(!det || n==m);
1293 for (unsigned c0=0; c0<n && r0<m-1; ++c0) {
1294 int indx = pivot(r0, c0, true);
1298 return 0; // leaves *this in a messy state
1303 for (unsigned r2=r0+1; r2<m; ++r2) {
1304 for (unsigned c=c0+1; c<n; ++c)
1305 this->m[r2*n+c] = (this->m[r0*n+c0]*this->m[r2*n+c] - this->m[r2*n+c0]*this->m[r0*n+c]).expand();
1306 // fill up left hand side with zeros
1307 for (unsigned c=r0; c<=c0; ++c)
1308 this->m[r2*n+c] = _ex0;
1311 // save space by deleting no longer needed elements
1312 for (unsigned c=r0+1; c<n; ++c)
1313 this->m[r0*n+c] = _ex0;
1318 // clear remaining rows
1319 for (unsigned r=r0+1; r<m; ++r) {
1320 for (unsigned c=0; c<n; ++c)
1321 this->m[r*n+c] = _ex0;
1328 /** Perform the steps of Bareiss' one-step fraction free elimination to bring
1329 * the matrix into an upper echelon form. Fraction free elimination means
1330 * that divide is used straightforwardly, without computing GCDs first. This
1331 * is possible, since we know the divisor at each step.
1333 * @param det may be set to true to save a lot of space if one is only
1334 * interested in the last element (i.e. for calculating determinants). The
1335 * others are set to zero in this case.
1336 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1337 * number of rows was swapped and 0 if the matrix is singular. */
1338 int matrix::fraction_free_elimination(const bool det)
1341 // (single-step fraction free elimination scheme, already known to Jordan)
1343 // Usual division-free elimination sets m[0](r,c) = m(r,c) and then sets
1344 // m[k+1](r,c) = m[k](k,k) * m[k](r,c) - m[k](r,k) * m[k](k,c).
1346 // Bareiss (fraction-free) elimination in addition divides that element
1347 // by m[k-1](k-1,k-1) for k>1, where it can be shown by means of the
1348 // Sylvester identity that this really divides m[k+1](r,c).
1350 // We also allow rational functions where the original prove still holds.
1351 // However, we must care for numerator and denominator separately and
1352 // "manually" work in the integral domains because of subtle cancellations
1353 // (see below). This blows up the bookkeeping a bit and the formula has
1354 // to be modified to expand like this (N{x} stands for numerator of x,
1355 // D{x} for denominator of x):
1356 // 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)}
1357 // -N{m[k](r,k)}*N{m[k](k,c)}*D{m[k](k,k)}*D{m[k](r,c)}
1358 // 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)}
1359 // where for k>1 we now divide N{m[k+1](r,c)} by
1360 // N{m[k-1](k-1,k-1)}
1361 // and D{m[k+1](r,c)} by
1362 // D{m[k-1](k-1,k-1)}.
1364 ensure_if_modifiable();
1365 const unsigned m = this->rows();
1366 const unsigned n = this->cols();
1367 GINAC_ASSERT(!det || n==m);
1376 // We populate temporary matrices to subsequently operate on. There is
1377 // one holding numerators and another holding denominators of entries.
1378 // This is a must since the evaluator (or even earlier mul's constructor)
1379 // might cancel some trivial element which causes divide() to fail. The
1380 // elements are normalized first (yes, even though this algorithm doesn't
1381 // need GCDs) since the elements of *this might be unnormalized, which
1382 // makes things more complicated than they need to be.
1383 matrix tmp_n(*this);
1384 matrix tmp_d(m,n); // for denominators, if needed
1385 exmap srl; // symbol replacement list
1386 exvector::const_iterator cit = this->m.begin(), citend = this->m.end();
1387 exvector::iterator tmp_n_it = tmp_n.m.begin(), tmp_d_it = tmp_d.m.begin();
1388 while (cit != citend) {
1389 ex nd = cit->normal().to_rational(srl).numer_denom();
1391 *tmp_n_it++ = nd.op(0);
1392 *tmp_d_it++ = nd.op(1);
1396 for (unsigned c0=0; c0<n && r0<m-1; ++c0) {
1397 int indx = tmp_n.pivot(r0, c0, true);
1406 // tmp_n's rows r0 and indx were swapped, do the same in tmp_d:
1407 for (unsigned c=c0; c<n; ++c)
1408 tmp_d.m[n*indx+c].swap(tmp_d.m[n*r0+c]);
1410 for (unsigned r2=r0+1; r2<m; ++r2) {
1411 for (unsigned c=c0+1; c<n; ++c) {
1412 dividend_n = (tmp_n.m[r0*n+c0]*tmp_n.m[r2*n+c]*
1413 tmp_d.m[r2*n+c0]*tmp_d.m[r0*n+c]
1414 -tmp_n.m[r2*n+c0]*tmp_n.m[r0*n+c]*
1415 tmp_d.m[r0*n+c0]*tmp_d.m[r2*n+c]).expand();
1416 dividend_d = (tmp_d.m[r2*n+c0]*tmp_d.m[r0*n+c]*
1417 tmp_d.m[r0*n+c0]*tmp_d.m[r2*n+c]).expand();
1418 bool check = divide(dividend_n, divisor_n,
1419 tmp_n.m[r2*n+c], true);
1420 check &= divide(dividend_d, divisor_d,
1421 tmp_d.m[r2*n+c], true);
1422 GINAC_ASSERT(check);
1424 // fill up left hand side with zeros
1425 for (unsigned c=r0; c<=c0; ++c)
1426 tmp_n.m[r2*n+c] = _ex0;
1428 if (c0<n && r0<m-1) {
1429 // compute next iteration's divisor
1430 divisor_n = tmp_n.m[r0*n+c0].expand();
1431 divisor_d = tmp_d.m[r0*n+c0].expand();
1433 // save space by deleting no longer needed elements
1434 for (unsigned c=0; c<n; ++c) {
1435 tmp_n.m[r0*n+c] = _ex0;
1436 tmp_d.m[r0*n+c] = _ex1;
1443 // clear remaining rows
1444 for (unsigned r=r0+1; r<m; ++r) {
1445 for (unsigned c=0; c<n; ++c)
1446 tmp_n.m[r*n+c] = _ex0;
1449 // repopulate *this matrix:
1450 exvector::iterator it = this->m.begin(), itend = this->m.end();
1451 tmp_n_it = tmp_n.m.begin();
1452 tmp_d_it = tmp_d.m.begin();
1454 *it++ = ((*tmp_n_it++)/(*tmp_d_it++)).subs(srl, subs_options::no_pattern);
1460 /** Partial pivoting method for matrix elimination schemes.
1461 * Usual pivoting (symbolic==false) returns the index to the element with the
1462 * largest absolute value in column ro and swaps the current row with the one
1463 * where the element was found. With (symbolic==true) it does the same thing
1464 * with the first non-zero element.
1466 * @param ro is the row from where to begin
1467 * @param co is the column to be inspected
1468 * @param symbolic signal if we want the first non-zero element to be pivoted
1469 * (true) or the one with the largest absolute value (false).
1470 * @return 0 if no interchange occured, -1 if all are zero (usually signaling
1471 * a degeneracy) and positive integer k means that rows ro and k were swapped.
1473 int matrix::pivot(unsigned ro, unsigned co, bool symbolic)
1477 // search first non-zero element in column co beginning at row ro
1478 while ((k<row) && (this->m[k*col+co].expand().is_zero()))
1481 // search largest element in column co beginning at row ro
1482 GINAC_ASSERT(is_exactly_a<numeric>(this->m[k*col+co]));
1483 unsigned kmax = k+1;
1484 numeric mmax = abs(ex_to<numeric>(m[kmax*col+co]));
1486 GINAC_ASSERT(is_exactly_a<numeric>(this->m[kmax*col+co]));
1487 numeric tmp = ex_to<numeric>(this->m[kmax*col+co]);
1488 if (abs(tmp) > mmax) {
1494 if (!mmax.is_zero())
1498 // all elements in column co below row ro vanish
1501 // matrix needs no pivoting
1503 // matrix needs pivoting, so swap rows k and ro
1504 ensure_if_modifiable();
1505 for (unsigned c=0; c<col; ++c)
1506 this->m[k*col+c].swap(this->m[ro*col+c]);
1511 ex lst_to_matrix(const lst & l)
1513 lst::const_iterator itr, itc;
1515 // Find number of rows and columns
1516 size_t rows = l.nops(), cols = 0;
1517 for (itr = l.begin(); itr != l.end(); ++itr) {
1518 if (!is_a<lst>(*itr))
1519 throw (std::invalid_argument("lst_to_matrix: argument must be a list of lists"));
1520 if (itr->nops() > cols)
1524 // Allocate and fill matrix
1525 matrix &M = *new matrix(rows, cols);
1526 M.setflag(status_flags::dynallocated);
1529 for (itr = l.begin(), i = 0; itr != l.end(); ++itr, ++i) {
1531 for (itc = ex_to<lst>(*itr).begin(), j = 0; itc != ex_to<lst>(*itr).end(); ++itc, ++j)
1538 ex diag_matrix(const lst & l)
1540 lst::const_iterator it;
1541 size_t dim = l.nops();
1543 // Allocate and fill matrix
1544 matrix &M = *new matrix(dim, dim);
1545 M.setflag(status_flags::dynallocated);
1548 for (it = l.begin(), i = 0; it != l.end(); ++it, ++i)
1554 ex unit_matrix(unsigned r, unsigned c)
1556 matrix &Id = *new matrix(r, c);
1557 Id.setflag(status_flags::dynallocated);
1558 for (unsigned i=0; i<r && i<c; i++)
1564 ex symbolic_matrix(unsigned r, unsigned c, const std::string & base_name, const std::string & tex_base_name)
1566 matrix &M = *new matrix(r, c);
1567 M.setflag(status_flags::dynallocated | status_flags::evaluated);
1569 bool long_format = (r > 10 || c > 10);
1570 bool single_row = (r == 1 || c == 1);
1572 for (unsigned i=0; i<r; i++) {
1573 for (unsigned j=0; j<c; j++) {
1574 std::ostringstream s1, s2;
1576 s2 << tex_base_name << "_{";
1587 s1 << '_' << i << '_' << j;
1588 s2 << i << ';' << j << "}";
1591 s2 << i << j << '}';
1594 M(i, j) = symbol(s1.str(), s2.str());
1601 ex reduced_matrix(const matrix& m, unsigned r, unsigned c)
1603 if (r+1>m.rows() || c+1>m.cols() || m.cols()<2 || m.rows()<2)
1604 throw std::runtime_error("minor_matrix(): index out of bounds");
1606 const unsigned rows = m.rows()-1;
1607 const unsigned cols = m.cols()-1;
1608 matrix &M = *new matrix(rows, cols);
1609 M.setflag(status_flags::dynallocated | status_flags::evaluated);
1621 M(ro2,co2) = m(ro, co);
1632 ex sub_matrix(const matrix&m, unsigned r, unsigned nr, unsigned c, unsigned nc)
1634 if (r+nr>m.rows() || c+nc>m.cols())
1635 throw std::runtime_error("sub_matrix(): index out of bounds");
1637 matrix &M = *new matrix(nr, nc);
1638 M.setflag(status_flags::dynallocated | status_flags::evaluated);
1640 for (unsigned ro=0; ro<nr; ++ro) {
1641 for (unsigned co=0; co<nc; ++co) {
1642 M(ro,co) = m(ro+r,co+c);
1649 } // namespace GiNaC