3 * Implementation of symbolic matrices */
6 * GiNaC Copyright (C) 1999-2015 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
31 #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() : 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) : row(r), col(c), m(r*c, _ex0)
73 setflag(status_flags::not_shareable);
76 /** Construct matrix from (flat) list of elements. If the list has fewer
77 * elements than the matrix, the remaining matrix elements are set to zero.
78 * If the list has more elements than the matrix, the excessive elements are
80 matrix::matrix(unsigned r, unsigned c, const lst & l)
81 : row(r), col(c), m(r*c, _ex0)
83 setflag(status_flags::not_shareable);
90 break; // matrix smaller than list: throw away excessive elements
96 /** Construct a matrix from an 2 dimensional initializer list.
97 * Throws an exception if some row has a different length than all the others.
99 matrix::matrix(std::initializer_list<std::initializer_list<ex>> l)
100 : row(l.size()), col(l.begin()->size())
102 setflag(status_flags::not_shareable);
105 for (const auto & r : l) {
107 for (const auto & e : r) {
112 throw std::invalid_argument("matrix::matrix{{}}: wrong dimension");
118 /** Ctor from representation, for internal use only. */
119 matrix::matrix(unsigned r, unsigned c, const exvector & m2)
120 : row(r), col(c), m(m2)
122 setflag(status_flags::not_shareable);
124 matrix::matrix(unsigned r, unsigned c, exvector && m2)
125 : row(r), col(c), m(std::move(m2))
127 setflag(status_flags::not_shareable);
134 void matrix::read_archive(const archive_node &n, lst &sym_lst)
136 inherited::read_archive(n, sym_lst);
138 if (!(n.find_unsigned("row", row)) || !(n.find_unsigned("col", col)))
139 throw (std::runtime_error("unknown matrix dimensions in archive"));
140 m.reserve(row * col);
141 // XXX: default ctor inserts a zero element, we need to erase it here.
143 auto first = n.find_first("m");
144 auto last = n.find_last("m");
146 for (auto i=first; i != last; ++i) {
148 n.find_ex_by_loc(i, e, sym_lst);
152 GINAC_BIND_UNARCHIVER(matrix);
154 void matrix::archive(archive_node &n) const
156 inherited::archive(n);
157 n.add_unsigned("row", row);
158 n.add_unsigned("col", col);
165 // functions overriding virtual functions from base classes
170 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
172 for (unsigned ro=0; ro<row; ++ro) {
174 for (unsigned co=0; co<col; ++co) {
175 m[ro*col+co].print(c);
186 void matrix::do_print(const print_context & c, unsigned level) const
189 print_elements(c, "[", "]", ",", ",");
193 void matrix::do_print_latex(const print_latex & c, unsigned level) const
195 c.s << "\\left(\\begin{array}{" << std::string(col,'c') << "}";
196 print_elements(c, "", "", "\\\\", "&");
197 c.s << "\\end{array}\\right)";
200 void matrix::do_print_python_repr(const print_python_repr & c, unsigned level) const
202 c.s << class_name() << '(';
203 print_elements(c, "[", "]", ",", ",");
207 /** nops is defined to be rows x columns. */
208 size_t matrix::nops() const
210 return static_cast<size_t>(row) * static_cast<size_t>(col);
213 /** returns matrix entry at position (i/col, i%col). */
214 ex matrix::op(size_t i) const
216 GINAC_ASSERT(i<nops());
221 /** returns writable matrix entry at position (i/col, i%col). */
222 ex & matrix::let_op(size_t i)
224 GINAC_ASSERT(i<nops());
226 ensure_if_modifiable();
230 /** Evaluate matrix entry by entry. */
231 ex matrix::eval(int level) const
233 // check if we have to do anything at all
234 if ((level==1)&&(flags & status_flags::evaluated))
238 if (level == -max_recursion_level)
239 throw (std::runtime_error("matrix::eval(): recursion limit exceeded"));
241 // eval() entry by entry
242 exvector m2(row*col);
244 for (unsigned r=0; r<row; ++r)
245 for (unsigned c=0; c<col; ++c)
246 m2[r*col+c] = m[r*col+c].eval(level);
248 return dynallocate<matrix>(row, col, std::move(m2)).setflag(status_flags::evaluated);
251 ex matrix::subs(const exmap & mp, unsigned options) const
253 exvector m2(row * col);
254 for (unsigned r=0; r<row; ++r)
255 for (unsigned c=0; c<col; ++c)
256 m2[r*col+c] = m[r*col+c].subs(mp, options);
258 return matrix(row, col, std::move(m2)).subs_one_level(mp, options);
261 /** Complex conjugate every matrix entry. */
262 ex matrix::conjugate() const
264 std::unique_ptr<exvector> ev(nullptr);
265 for (auto i=m.begin(); i!=m.end(); ++i) {
266 ex x = i->conjugate();
271 if (are_ex_trivially_equal(x, *i)) {
274 ev.reset(new exvector);
275 ev->reserve(m.size());
276 for (auto j=m.begin(); j!=i; ++j) {
282 return matrix(row, col, std::move(*ev));
287 ex matrix::real_part() const
292 v.push_back(i.real_part());
293 return matrix(row, col, std::move(v));
296 ex matrix::imag_part() const
301 v.push_back(i.imag_part());
302 return matrix(row, col, std::move(v));
307 int matrix::compare_same_type(const basic & other) const
309 GINAC_ASSERT(is_exactly_a<matrix>(other));
310 const matrix &o = static_cast<const matrix &>(other);
312 // compare number of rows
314 return row < o.rows() ? -1 : 1;
316 // compare number of columns
318 return col < o.cols() ? -1 : 1;
320 // equal number of rows and columns, compare individual elements
322 for (unsigned r=0; r<row; ++r) {
323 for (unsigned c=0; c<col; ++c) {
324 cmpval = ((*this)(r,c)).compare(o(r,c));
325 if (cmpval!=0) return cmpval;
328 // all elements are equal => matrices are equal;
332 bool matrix::match_same_type(const basic & other) const
334 GINAC_ASSERT(is_exactly_a<matrix>(other));
335 const matrix & o = static_cast<const matrix &>(other);
337 // The number of rows and columns must be the same. This is necessary to
338 // prevent a 2x3 matrix from matching a 3x2 one.
339 return row == o.rows() && col == o.cols();
342 /** Automatic symbolic evaluation of an indexed matrix. */
343 ex matrix::eval_indexed(const basic & i) const
345 GINAC_ASSERT(is_a<indexed>(i));
346 GINAC_ASSERT(is_a<matrix>(i.op(0)));
348 bool all_indices_unsigned = static_cast<const indexed &>(i).all_index_values_are(info_flags::nonnegint);
353 // One index, must be one-dimensional vector
354 if (row != 1 && col != 1)
355 throw (std::runtime_error("matrix::eval_indexed(): vector must have exactly 1 index"));
357 const idx & i1 = ex_to<idx>(i.op(1));
362 if (!i1.get_dim().is_equal(row))
363 throw (std::runtime_error("matrix::eval_indexed(): dimension of index must match number of vector elements"));
365 // Index numeric -> return vector element
366 if (all_indices_unsigned) {
367 unsigned n1 = ex_to<numeric>(i1.get_value()).to_int();
369 throw (std::runtime_error("matrix::eval_indexed(): value of index exceeds number of vector elements"));
370 return (*this)(n1, 0);
376 if (!i1.get_dim().is_equal(col))
377 throw (std::runtime_error("matrix::eval_indexed(): dimension of index must match number of vector elements"));
379 // Index numeric -> return vector element
380 if (all_indices_unsigned) {
381 unsigned n1 = ex_to<numeric>(i1.get_value()).to_int();
383 throw (std::runtime_error("matrix::eval_indexed(): value of index exceeds number of vector elements"));
384 return (*this)(0, n1);
388 } else if (i.nops() == 3) {
391 const idx & i1 = ex_to<idx>(i.op(1));
392 const idx & i2 = ex_to<idx>(i.op(2));
394 if (!i1.get_dim().is_equal(row))
395 throw (std::runtime_error("matrix::eval_indexed(): dimension of first index must match number of rows"));
396 if (!i2.get_dim().is_equal(col))
397 throw (std::runtime_error("matrix::eval_indexed(): dimension of second index must match number of columns"));
399 // Pair of dummy indices -> compute trace
400 if (is_dummy_pair(i1, i2))
403 // Both indices numeric -> return matrix element
404 if (all_indices_unsigned) {
405 unsigned n1 = ex_to<numeric>(i1.get_value()).to_int(), n2 = ex_to<numeric>(i2.get_value()).to_int();
407 throw (std::runtime_error("matrix::eval_indexed(): value of first index exceeds number of rows"));
409 throw (std::runtime_error("matrix::eval_indexed(): value of second index exceeds number of columns"));
410 return (*this)(n1, n2);
414 throw (std::runtime_error("matrix::eval_indexed(): matrix must have exactly 2 indices"));
419 /** Sum of two indexed matrices. */
420 ex matrix::add_indexed(const ex & self, const ex & other) const
422 GINAC_ASSERT(is_a<indexed>(self));
423 GINAC_ASSERT(is_a<matrix>(self.op(0)));
424 GINAC_ASSERT(is_a<indexed>(other));
425 GINAC_ASSERT(self.nops() == 2 || self.nops() == 3);
427 // Only add two matrices
428 if (is_a<matrix>(other.op(0))) {
429 GINAC_ASSERT(other.nops() == 2 || other.nops() == 3);
431 const matrix &self_matrix = ex_to<matrix>(self.op(0));
432 const matrix &other_matrix = ex_to<matrix>(other.op(0));
434 if (self.nops() == 2 && other.nops() == 2) { // vector + vector
436 if (self_matrix.row == other_matrix.row)
437 return indexed(self_matrix.add(other_matrix), self.op(1));
438 else if (self_matrix.row == other_matrix.col)
439 return indexed(self_matrix.add(other_matrix.transpose()), self.op(1));
441 } else if (self.nops() == 3 && other.nops() == 3) { // matrix + matrix
443 if (self.op(1).is_equal(other.op(1)) && self.op(2).is_equal(other.op(2)))
444 return indexed(self_matrix.add(other_matrix), self.op(1), self.op(2));
445 else if (self.op(1).is_equal(other.op(2)) && self.op(2).is_equal(other.op(1)))
446 return indexed(self_matrix.add(other_matrix.transpose()), self.op(1), self.op(2));
451 // Don't know what to do, return unevaluated sum
455 /** Product of an indexed matrix with a number. */
456 ex matrix::scalar_mul_indexed(const ex & self, const numeric & other) const
458 GINAC_ASSERT(is_a<indexed>(self));
459 GINAC_ASSERT(is_a<matrix>(self.op(0)));
460 GINAC_ASSERT(self.nops() == 2 || self.nops() == 3);
462 const matrix &self_matrix = ex_to<matrix>(self.op(0));
464 if (self.nops() == 2)
465 return indexed(self_matrix.mul(other), self.op(1));
466 else // self.nops() == 3
467 return indexed(self_matrix.mul(other), self.op(1), self.op(2));
470 /** Contraction of an indexed matrix with something else. */
471 bool matrix::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
473 GINAC_ASSERT(is_a<indexed>(*self));
474 GINAC_ASSERT(is_a<indexed>(*other));
475 GINAC_ASSERT(self->nops() == 2 || self->nops() == 3);
476 GINAC_ASSERT(is_a<matrix>(self->op(0)));
478 // Only contract with other matrices
479 if (!is_a<matrix>(other->op(0)))
482 GINAC_ASSERT(other->nops() == 2 || other->nops() == 3);
484 const matrix &self_matrix = ex_to<matrix>(self->op(0));
485 const matrix &other_matrix = ex_to<matrix>(other->op(0));
487 if (self->nops() == 2) {
489 if (other->nops() == 2) { // vector * vector (scalar product)
491 if (self_matrix.col == 1) {
492 if (other_matrix.col == 1) {
493 // Column vector * column vector, transpose first vector
494 *self = self_matrix.transpose().mul(other_matrix)(0, 0);
496 // Column vector * row vector, swap factors
497 *self = other_matrix.mul(self_matrix)(0, 0);
500 if (other_matrix.col == 1) {
501 // Row vector * column vector, perfect
502 *self = self_matrix.mul(other_matrix)(0, 0);
504 // Row vector * row vector, transpose second vector
505 *self = self_matrix.mul(other_matrix.transpose())(0, 0);
511 } else { // vector * matrix
513 // B_i * A_ij = (B*A)_j (B is row vector)
514 if (is_dummy_pair(self->op(1), other->op(1))) {
515 if (self_matrix.row == 1)
516 *self = indexed(self_matrix.mul(other_matrix), other->op(2));
518 *self = indexed(self_matrix.transpose().mul(other_matrix), other->op(2));
523 // B_j * A_ij = (A*B)_i (B is column vector)
524 if (is_dummy_pair(self->op(1), other->op(2))) {
525 if (self_matrix.col == 1)
526 *self = indexed(other_matrix.mul(self_matrix), other->op(1));
528 *self = indexed(other_matrix.mul(self_matrix.transpose()), other->op(1));
534 } else if (other->nops() == 3) { // matrix * matrix
536 // A_ij * B_jk = (A*B)_ik
537 if (is_dummy_pair(self->op(2), other->op(1))) {
538 *self = indexed(self_matrix.mul(other_matrix), self->op(1), other->op(2));
543 // A_ij * B_kj = (A*Btrans)_ik
544 if (is_dummy_pair(self->op(2), other->op(2))) {
545 *self = indexed(self_matrix.mul(other_matrix.transpose()), self->op(1), other->op(1));
550 // A_ji * B_jk = (Atrans*B)_ik
551 if (is_dummy_pair(self->op(1), other->op(1))) {
552 *self = indexed(self_matrix.transpose().mul(other_matrix), self->op(2), other->op(2));
557 // A_ji * B_kj = (B*A)_ki
558 if (is_dummy_pair(self->op(1), other->op(2))) {
559 *self = indexed(other_matrix.mul(self_matrix), other->op(1), self->op(2));
570 // non-virtual functions in this class
577 * @exception logic_error (incompatible matrices) */
578 matrix matrix::add(const matrix & other) const
580 if (col != other.col || row != other.row)
581 throw std::logic_error("matrix::add(): incompatible matrices");
583 exvector sum(this->m);
584 auto ci = other.m.begin();
588 return matrix(row, col, std::move(sum));
592 /** Difference of matrices.
594 * @exception logic_error (incompatible matrices) */
595 matrix matrix::sub(const matrix & other) const
597 if (col != other.col || row != other.row)
598 throw std::logic_error("matrix::sub(): incompatible matrices");
600 exvector dif(this->m);
601 auto ci = other.m.begin();
605 return matrix(row, col, std::move(dif));
609 /** Product of matrices.
611 * @exception logic_error (incompatible matrices) */
612 matrix matrix::mul(const matrix & other) const
614 if (this->cols() != other.rows())
615 throw std::logic_error("matrix::mul(): incompatible matrices");
617 exvector prod(this->rows()*other.cols());
619 for (unsigned r1=0; r1<this->rows(); ++r1) {
620 for (unsigned c=0; c<this->cols(); ++c) {
621 // Quick test: can we shortcut?
622 if (m[r1*col+c].is_zero())
624 for (unsigned r2=0; r2<other.cols(); ++r2)
625 prod[r1*other.col+r2] += (m[r1*col+c] * other.m[c*other.col+r2]);
628 return matrix(row, other.col, std::move(prod));
632 /** Product of matrix and scalar. */
633 matrix matrix::mul(const numeric & other) const
635 exvector prod(row * col);
637 for (unsigned r=0; r<row; ++r)
638 for (unsigned c=0; c<col; ++c)
639 prod[r*col+c] = m[r*col+c] * other;
641 return matrix(row, col, std::move(prod));
645 /** Product of matrix and scalar expression. */
646 matrix matrix::mul_scalar(const ex & other) const
648 if (other.return_type() != return_types::commutative)
649 throw std::runtime_error("matrix::mul_scalar(): non-commutative scalar");
651 exvector prod(row * col);
653 for (unsigned r=0; r<row; ++r)
654 for (unsigned c=0; c<col; ++c)
655 prod[r*col+c] = m[r*col+c] * other;
657 return matrix(row, col, std::move(prod));
661 /** Power of a matrix. Currently handles integer exponents only. */
662 matrix matrix::pow(const ex & expn) const
665 throw (std::logic_error("matrix::pow(): matrix not square"));
667 if (is_exactly_a<numeric>(expn)) {
668 // Integer cases are computed by successive multiplication, using the
669 // obvious shortcut of storing temporaries, like A^4 == (A*A)*(A*A).
670 if (expn.info(info_flags::integer)) {
671 numeric b = ex_to<numeric>(expn);
673 if (expn.info(info_flags::negative)) {
680 for (unsigned r=0; r<row; ++r)
684 // This loop computes the representation of b in base 2 from right
685 // to left and multiplies the factors whenever needed. Note
686 // that this is not entirely optimal but close to optimal and
687 // "better" algorithms are much harder to implement. (See Knuth,
688 // TAoCP2, section "Evaluation of Powers" for a good discussion.)
689 while (b!=*_num1_p) {
694 b /= *_num2_p; // still integer.
700 throw (std::runtime_error("matrix::pow(): don't know how to handle exponent"));
704 /** operator() to access elements for reading.
706 * @param ro row of element
707 * @param co column of element
708 * @exception range_error (index out of range) */
709 const ex & matrix::operator() (unsigned ro, unsigned co) const
711 if (ro>=row || co>=col)
712 throw (std::range_error("matrix::operator(): index out of range"));
718 /** operator() to access elements for writing.
720 * @param ro row of element
721 * @param co column of element
722 * @exception range_error (index out of range) */
723 ex & matrix::operator() (unsigned ro, unsigned co)
725 if (ro>=row || co>=col)
726 throw (std::range_error("matrix::operator(): index out of range"));
728 ensure_if_modifiable();
733 /** Transposed of an m x n matrix, producing a new n x m matrix object that
734 * represents the transposed. */
735 matrix matrix::transpose() const
737 exvector trans(this->cols()*this->rows());
739 for (unsigned r=0; r<this->cols(); ++r)
740 for (unsigned c=0; c<this->rows(); ++c)
741 trans[r*this->rows()+c] = m[c*this->cols()+r];
743 return matrix(this->cols(), this->rows(), std::move(trans));
746 /** Determinant of square matrix. This routine doesn't actually calculate the
747 * determinant, it only implements some heuristics about which algorithm to
748 * run. If all the elements of the matrix are elements of an integral domain
749 * the determinant is also in that integral domain and the result is expanded
750 * only. If one or more elements are from a quotient field the determinant is
751 * usually also in that quotient field and the result is normalized before it
752 * is returned. This implies that the determinant of the symbolic 2x2 matrix
753 * [[a/(a-b),1],[b/(a-b),1]] is returned as unity. (In this respect, it
754 * behaves like MapleV and unlike Mathematica.)
756 * @param algo allows to chose an algorithm
757 * @return the determinant as a new expression
758 * @exception logic_error (matrix not square)
759 * @see determinant_algo */
760 ex matrix::determinant(unsigned algo) const
763 throw (std::logic_error("matrix::determinant(): matrix not square"));
764 GINAC_ASSERT(row*col==m.capacity());
766 // Gather some statistical information about this matrix:
767 bool numeric_flag = true;
768 bool normal_flag = false;
769 unsigned sparse_count = 0; // counts non-zero elements
771 if (!r.info(info_flags::numeric))
772 numeric_flag = false;
773 exmap srl; // symbol replacement list
774 ex rtest = r.to_rational(srl);
775 if (!rtest.is_zero())
777 if (!rtest.info(info_flags::crational_polynomial) &&
778 rtest.info(info_flags::rational_function))
782 // Here is the heuristics in case this routine has to decide:
783 if (algo == determinant_algo::automatic) {
784 // Minor expansion is generally a good guess:
785 algo = determinant_algo::laplace;
786 // Does anybody know when a matrix is really sparse?
787 // Maybe <~row/2.236 nonzero elements average in a row?
788 if (row>3 && 5*sparse_count<=row*col)
789 algo = determinant_algo::bareiss;
790 // Purely numeric matrix can be handled by Gauss elimination.
791 // This overrides any prior decisions.
793 algo = determinant_algo::gauss;
796 // Trap the trivial case here, since some algorithms don't like it
798 // for consistency with non-trivial determinants...
800 return m[0].normal();
802 return m[0].expand();
805 // Compute the determinant
807 case determinant_algo::gauss: {
810 int sign = tmp.gauss_elimination(true);
811 for (unsigned d=0; d<row; ++d)
812 det *= tmp.m[d*col+d];
814 return (sign*det).normal();
816 return (sign*det).normal().expand();
818 case determinant_algo::bareiss: {
821 sign = tmp.fraction_free_elimination(true);
823 return (sign*tmp.m[row*col-1]).normal();
825 return (sign*tmp.m[row*col-1]).expand();
827 case determinant_algo::divfree: {
830 sign = tmp.division_free_elimination(true);
833 ex det = tmp.m[row*col-1];
834 // factor out accumulated bogus slag
835 for (unsigned d=0; d<row-2; ++d)
836 for (unsigned j=0; j<row-d-2; ++j)
837 det = (det/tmp.m[d*col+d]).normal();
840 case determinant_algo::laplace:
842 // This is the minor expansion scheme. We always develop such
843 // that the smallest minors (i.e, the trivial 1x1 ones) are on the
844 // rightmost column. For this to be efficient, empirical tests
845 // have shown that the emptiest columns (i.e. the ones with most
846 // zeros) should be the ones on the right hand side -- although
847 // this might seem counter-intuitive (and in contradiction to some
848 // literature like the FORM manual). Please go ahead and test it
849 // if you don't believe me! Therefore we presort the columns of
851 typedef std::pair<unsigned,unsigned> uintpair;
852 std::vector<uintpair> c_zeros; // number of zeros in column
853 for (unsigned c=0; c<col; ++c) {
855 for (unsigned r=0; r<row; ++r)
856 if (m[r*col+c].is_zero())
858 c_zeros.push_back(uintpair(acc,c));
860 std::sort(c_zeros.begin(),c_zeros.end());
861 std::vector<unsigned> pre_sort;
862 for (auto & i : c_zeros)
863 pre_sort.push_back(i.second);
864 std::vector<unsigned> pre_sort_test(pre_sort); // permutation_sign() modifies the vector so we make a copy here
865 int sign = permutation_sign(pre_sort_test.begin(), pre_sort_test.end());
866 exvector result(row*col); // represents sorted matrix
868 for (auto & it : pre_sort) {
869 for (unsigned r=0; r<row; ++r)
870 result[r*col+c] = m[r*col+it];
875 return (sign*matrix(row, col, std::move(result)).determinant_minor()).normal();
877 return sign*matrix(row, col, std::move(result)).determinant_minor();
883 /** Trace of a matrix. The result is normalized if it is in some quotient
884 * field and expanded only otherwise. This implies that the trace of the
885 * symbolic 2x2 matrix [[a/(a-b),x],[y,b/(b-a)]] is recognized to be unity.
887 * @return the sum of diagonal elements
888 * @exception logic_error (matrix not square) */
889 ex matrix::trace() const
892 throw (std::logic_error("matrix::trace(): matrix not square"));
895 for (unsigned r=0; r<col; ++r)
898 if (tr.info(info_flags::rational_function) &&
899 !tr.info(info_flags::crational_polynomial))
906 /** Characteristic Polynomial. Following mathematica notation the
907 * characteristic polynomial of a matrix M is defined as the determinant of
908 * (M - lambda * 1) where 1 stands for the unit matrix of the same dimension
909 * as M. Note that some CASs define it with a sign inside the determinant
910 * which gives rise to an overall sign if the dimension is odd. This method
911 * returns the characteristic polynomial collected in powers of lambda as a
914 * @return characteristic polynomial as new expression
915 * @exception logic_error (matrix not square)
916 * @see matrix::determinant() */
917 ex matrix::charpoly(const ex & lambda) const
920 throw (std::logic_error("matrix::charpoly(): matrix not square"));
922 bool numeric_flag = true;
924 if (!r.info(info_flags::numeric)) {
925 numeric_flag = false;
930 // The pure numeric case is traditionally rather common. Hence, it is
931 // trapped and we use Leverrier's algorithm which goes as row^3 for
932 // every coefficient. The expensive part is the matrix multiplication.
937 ex poly = power(lambda, row) - c*power(lambda, row-1);
938 for (unsigned i=1; i<row; ++i) {
939 for (unsigned j=0; j<row; ++j)
942 c = B.trace() / ex(i+1);
943 poly -= c*power(lambda, row-i-1);
953 for (unsigned r=0; r<col; ++r)
954 M.m[r*col+r] -= lambda;
956 return M.determinant().collect(lambda);
961 /** Inverse of this matrix.
963 * @return the inverted matrix
964 * @exception logic_error (matrix not square)
965 * @exception runtime_error (singular matrix) */
966 matrix matrix::inverse() const
969 throw (std::logic_error("matrix::inverse(): matrix not square"));
971 // This routine actually doesn't do anything fancy at all. We compute the
972 // inverse of the matrix A by solving the system A * A^{-1} == Id.
974 // First populate the identity matrix supposed to become the right hand side.
975 matrix identity(row,col);
976 for (unsigned i=0; i<row; ++i)
977 identity(i,i) = _ex1;
979 // Populate a dummy matrix of variables, just because of compatibility with
980 // matrix::solve() which wants this (for compatibility with under-determined
981 // systems of equations).
982 matrix vars(row,col);
983 for (unsigned r=0; r<row; ++r)
984 for (unsigned c=0; c<col; ++c)
985 vars(r,c) = symbol();
989 sol = this->solve(vars,identity);
990 } catch (const std::runtime_error & e) {
991 if (e.what()==std::string("matrix::solve(): inconsistent linear system"))
992 throw (std::runtime_error("matrix::inverse(): singular matrix"));
1000 /** Solve a linear system consisting of a m x n matrix and a m x p right hand
1001 * side by applying an elimination scheme to the augmented matrix.
1003 * @param vars n x p matrix, all elements must be symbols
1004 * @param rhs m x p matrix
1005 * @param algo selects the solving algorithm
1006 * @return n x p solution matrix
1007 * @exception logic_error (incompatible matrices)
1008 * @exception invalid_argument (1st argument must be matrix of symbols)
1009 * @exception runtime_error (inconsistent linear system)
1010 * @see solve_algo */
1011 matrix matrix::solve(const matrix & vars,
1013 unsigned algo) const
1015 const unsigned m = this->rows();
1016 const unsigned n = this->cols();
1017 const unsigned p = rhs.cols();
1020 if ((rhs.rows() != m) || (vars.rows() != n) || (vars.col != p))
1021 throw (std::logic_error("matrix::solve(): incompatible matrices"));
1022 for (unsigned ro=0; ro<n; ++ro)
1023 for (unsigned co=0; co<p; ++co)
1024 if (!vars(ro,co).info(info_flags::symbol))
1025 throw (std::invalid_argument("matrix::solve(): 1st argument must be matrix of symbols"));
1027 // build the augmented matrix of *this with rhs attached to the right
1029 for (unsigned r=0; r<m; ++r) {
1030 for (unsigned c=0; c<n; ++c)
1031 aug.m[r*(n+p)+c] = this->m[r*n+c];
1032 for (unsigned c=0; c<p; ++c)
1033 aug.m[r*(n+p)+c+n] = rhs.m[r*p+c];
1036 // Gather some statistical information about the augmented matrix:
1037 bool numeric_flag = true;
1038 for (auto & r : aug.m) {
1039 if (!r.info(info_flags::numeric)) {
1040 numeric_flag = false;
1045 // Here is the heuristics in case this routine has to decide:
1046 if (algo == solve_algo::automatic) {
1047 // Bareiss (fraction-free) elimination is generally a good guess:
1048 algo = solve_algo::bareiss;
1049 // For m<3, Bareiss elimination is equivalent to division free
1050 // elimination but has more logistic overhead
1052 algo = solve_algo::divfree;
1053 // This overrides any prior decisions.
1055 algo = solve_algo::gauss;
1058 // Eliminate the augmented matrix:
1060 case solve_algo::gauss:
1061 aug.gauss_elimination();
1063 case solve_algo::divfree:
1064 aug.division_free_elimination();
1066 case solve_algo::bareiss:
1068 aug.fraction_free_elimination();
1071 // assemble the solution matrix:
1073 for (unsigned co=0; co<p; ++co) {
1074 unsigned last_assigned_sol = n+1;
1075 for (int r=m-1; r>=0; --r) {
1076 unsigned fnz = 1; // first non-zero in row
1077 while ((fnz<=n) && (aug.m[r*(n+p)+(fnz-1)].is_zero()))
1080 // row consists only of zeros, corresponding rhs must be 0, too
1081 if (!aug.m[r*(n+p)+n+co].is_zero()) {
1082 throw (std::runtime_error("matrix::solve(): inconsistent linear system"));
1085 // assign solutions for vars between fnz+1 and
1086 // last_assigned_sol-1: free parameters
1087 for (unsigned c=fnz; c<last_assigned_sol-1; ++c)
1088 sol(c,co) = vars.m[c*p+co];
1089 ex e = aug.m[r*(n+p)+n+co];
1090 for (unsigned c=fnz; c<n; ++c)
1091 e -= aug.m[r*(n+p)+c]*sol.m[c*p+co];
1092 sol(fnz-1,co) = (e/(aug.m[r*(n+p)+(fnz-1)])).normal();
1093 last_assigned_sol = fnz;
1096 // assign solutions for vars between 1 and
1097 // last_assigned_sol-1: free parameters
1098 for (unsigned ro=0; ro<last_assigned_sol-1; ++ro)
1099 sol(ro,co) = vars(ro,co);
1106 /** Compute the rank of this matrix. */
1107 unsigned matrix::rank() const
1110 // Transform this matrix into upper echelon form and then count the
1111 // number of non-zero rows.
1113 GINAC_ASSERT(row*col==m.capacity());
1115 // Actually, any elimination scheme will do since we are only
1116 // interested in the echelon matrix' zeros.
1117 matrix to_eliminate = *this;
1118 to_eliminate.fraction_free_elimination();
1120 unsigned r = row*col; // index of last non-zero element
1122 if (!to_eliminate.m[r].is_zero())
1131 /** Recursive determinant for small matrices having at least one symbolic
1132 * entry. The basic algorithm, known as Laplace-expansion, is enhanced by
1133 * some bookkeeping to avoid calculation of the same submatrices ("minors")
1134 * more than once. According to W.M.Gentleman and S.C.Johnson this algorithm
1135 * is better than elimination schemes for matrices of sparse multivariate
1136 * polynomials and also for matrices of dense univariate polynomials if the
1137 * matrix' dimension is larger than 7.
1139 * @return the determinant as a new expression (in expanded form)
1140 * @see matrix::determinant() */
1141 ex matrix::determinant_minor() const
1143 // for small matrices the algorithm does not make any sense:
1144 const unsigned n = this->cols();
1146 return m[0].expand();
1148 return (m[0]*m[3]-m[2]*m[1]).expand();
1150 return (m[0]*m[4]*m[8]-m[0]*m[5]*m[7]-
1151 m[1]*m[3]*m[8]+m[2]*m[3]*m[7]+
1152 m[1]*m[5]*m[6]-m[2]*m[4]*m[6]).expand();
1154 // This algorithm can best be understood by looking at a naive
1155 // implementation of Laplace-expansion, like this one:
1157 // matrix minorM(this->rows()-1,this->cols()-1);
1158 // for (unsigned r1=0; r1<this->rows(); ++r1) {
1159 // // shortcut if element(r1,0) vanishes
1160 // if (m[r1*col].is_zero())
1162 // // assemble the minor matrix
1163 // for (unsigned r=0; r<minorM.rows(); ++r) {
1164 // for (unsigned c=0; c<minorM.cols(); ++c) {
1166 // minorM(r,c) = m[r*col+c+1];
1168 // minorM(r,c) = m[(r+1)*col+c+1];
1171 // // recurse down and care for sign:
1173 // det -= m[r1*col] * minorM.determinant_minor();
1175 // det += m[r1*col] * minorM.determinant_minor();
1177 // return det.expand();
1178 // What happens is that while proceeding down many of the minors are
1179 // computed more than once. In particular, there are binomial(n,k)
1180 // kxk minors and each one is computed factorial(n-k) times. Therefore
1181 // it is reasonable to store the results of the minors. We proceed from
1182 // right to left. At each column c we only need to retrieve the minors
1183 // calculated in step c-1. We therefore only have to store at most
1184 // 2*binomial(n,n/2) minors.
1186 // Unique flipper counter for partitioning into minors
1187 std::vector<unsigned> Pkey;
1189 // key for minor determinant (a subpartition of Pkey)
1190 std::vector<unsigned> Mkey;
1192 // we store our subminors in maps, keys being the rows they arise from
1193 typedef std::map<std::vector<unsigned>,class ex> Rmap;
1194 typedef std::map<std::vector<unsigned>,class ex>::value_type Rmap_value;
1198 // initialize A with last column:
1199 for (unsigned r=0; r<n; ++r) {
1200 Pkey.erase(Pkey.begin(),Pkey.end());
1202 A.insert(Rmap_value(Pkey,m[n*(r+1)-1]));
1204 // proceed from right to left through matrix
1205 for (int c=n-2; c>=0; --c) {
1206 Pkey.erase(Pkey.begin(),Pkey.end()); // don't change capacity
1207 Mkey.erase(Mkey.begin(),Mkey.end());
1208 for (unsigned i=0; i<n-c; ++i)
1210 unsigned fc = 0; // controls logic for our strange flipper counter
1213 for (unsigned r=0; r<n-c; ++r) {
1214 // maybe there is nothing to do?
1215 if (m[Pkey[r]*n+c].is_zero())
1217 // create the sorted key for all possible minors
1218 Mkey.erase(Mkey.begin(),Mkey.end());
1219 for (unsigned i=0; i<n-c; ++i)
1221 Mkey.push_back(Pkey[i]);
1222 // Fetch the minors and compute the new determinant
1224 det -= m[Pkey[r]*n+c]*A[Mkey];
1226 det += m[Pkey[r]*n+c]*A[Mkey];
1228 // prevent build-up of deep nesting of expressions saves time:
1230 // store the new determinant at its place in B:
1232 B.insert(Rmap_value(Pkey,det));
1233 // increment our strange flipper counter
1234 for (fc=n-c; fc>0; --fc) {
1236 if (Pkey[fc-1]<fc+c)
1240 for (unsigned j=fc; j<n-c; ++j)
1241 Pkey[j] = Pkey[j-1]+1;
1243 // next column, clear B and change the role of A and B:
1251 /** Perform the steps of an ordinary Gaussian elimination to bring the m x n
1252 * matrix into an upper echelon form. The algorithm is ok for matrices
1253 * with numeric coefficients but quite unsuited for symbolic matrices.
1255 * @param det may be set to true to save a lot of space if one is only
1256 * interested in the diagonal elements (i.e. for calculating determinants).
1257 * The others are set to zero in this case.
1258 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1259 * number of rows was swapped and 0 if the matrix is singular. */
1260 int matrix::gauss_elimination(const bool det)
1262 ensure_if_modifiable();
1263 const unsigned m = this->rows();
1264 const unsigned n = this->cols();
1265 GINAC_ASSERT(!det || n==m);
1269 for (unsigned c0=0; c0<n && r0<m-1; ++c0) {
1270 int indx = pivot(r0, c0, true);
1274 return 0; // leaves *this in a messy state
1279 for (unsigned r2=r0+1; r2<m; ++r2) {
1280 if (!this->m[r2*n+c0].is_zero()) {
1281 // yes, there is something to do in this row
1282 ex piv = this->m[r2*n+c0] / this->m[r0*n+c0];
1283 for (unsigned c=c0+1; c<n; ++c) {
1284 this->m[r2*n+c] -= piv * this->m[r0*n+c];
1285 if (!this->m[r2*n+c].info(info_flags::numeric))
1286 this->m[r2*n+c] = this->m[r2*n+c].normal();
1289 // fill up left hand side with zeros
1290 for (unsigned c=r0; c<=c0; ++c)
1291 this->m[r2*n+c] = _ex0;
1294 // save space by deleting no longer needed elements
1295 for (unsigned c=r0+1; c<n; ++c)
1296 this->m[r0*n+c] = _ex0;
1301 // clear remaining rows
1302 for (unsigned r=r0+1; r<m; ++r) {
1303 for (unsigned c=0; c<n; ++c)
1304 this->m[r*n+c] = _ex0;
1311 /** Perform the steps of division free elimination to bring the m x n matrix
1312 * into an upper echelon form.
1314 * @param det may be set to true to save a lot of space if one is only
1315 * interested in the diagonal elements (i.e. for calculating determinants).
1316 * The others are set to zero in this case.
1317 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1318 * number of rows was swapped and 0 if the matrix is singular. */
1319 int matrix::division_free_elimination(const bool det)
1321 ensure_if_modifiable();
1322 const unsigned m = this->rows();
1323 const unsigned n = this->cols();
1324 GINAC_ASSERT(!det || n==m);
1328 for (unsigned c0=0; c0<n && r0<m-1; ++c0) {
1329 int indx = pivot(r0, c0, true);
1333 return 0; // leaves *this in a messy state
1338 for (unsigned r2=r0+1; r2<m; ++r2) {
1339 for (unsigned c=c0+1; c<n; ++c)
1340 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();
1341 // fill up left hand side with zeros
1342 for (unsigned c=r0; c<=c0; ++c)
1343 this->m[r2*n+c] = _ex0;
1346 // save space by deleting no longer needed elements
1347 for (unsigned c=r0+1; c<n; ++c)
1348 this->m[r0*n+c] = _ex0;
1353 // clear remaining rows
1354 for (unsigned r=r0+1; r<m; ++r) {
1355 for (unsigned c=0; c<n; ++c)
1356 this->m[r*n+c] = _ex0;
1363 /** Perform the steps of Bareiss' one-step fraction free elimination to bring
1364 * the matrix into an upper echelon form. Fraction free elimination means
1365 * that divide is used straightforwardly, without computing GCDs first. This
1366 * is possible, since we know the divisor at each step.
1368 * @param det may be set to true to save a lot of space if one is only
1369 * interested in the last element (i.e. for calculating determinants). The
1370 * others are set to zero in this case.
1371 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1372 * number of rows was swapped and 0 if the matrix is singular. */
1373 int matrix::fraction_free_elimination(const bool det)
1376 // (single-step fraction free elimination scheme, already known to Jordan)
1378 // Usual division-free elimination sets m[0](r,c) = m(r,c) and then sets
1379 // m[k+1](r,c) = m[k](k,k) * m[k](r,c) - m[k](r,k) * m[k](k,c).
1381 // Bareiss (fraction-free) elimination in addition divides that element
1382 // by m[k-1](k-1,k-1) for k>1, where it can be shown by means of the
1383 // Sylvester identity that this really divides m[k+1](r,c).
1385 // We also allow rational functions where the original prove still holds.
1386 // However, we must care for numerator and denominator separately and
1387 // "manually" work in the integral domains because of subtle cancellations
1388 // (see below). This blows up the bookkeeping a bit and the formula has
1389 // to be modified to expand like this (N{x} stands for numerator of x,
1390 // D{x} for denominator of x):
1391 // 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)}
1392 // -N{m[k](r,k)}*N{m[k](k,c)}*D{m[k](k,k)}*D{m[k](r,c)}
1393 // 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)}
1394 // where for k>1 we now divide N{m[k+1](r,c)} by
1395 // N{m[k-1](k-1,k-1)}
1396 // and D{m[k+1](r,c)} by
1397 // D{m[k-1](k-1,k-1)}.
1399 ensure_if_modifiable();
1400 const unsigned m = this->rows();
1401 const unsigned n = this->cols();
1402 GINAC_ASSERT(!det || n==m);
1411 // We populate temporary matrices to subsequently operate on. There is
1412 // one holding numerators and another holding denominators of entries.
1413 // This is a must since the evaluator (or even earlier mul's constructor)
1414 // might cancel some trivial element which causes divide() to fail. The
1415 // elements are normalized first (yes, even though this algorithm doesn't
1416 // need GCDs) since the elements of *this might be unnormalized, which
1417 // makes things more complicated than they need to be.
1418 matrix tmp_n(*this);
1419 matrix tmp_d(m,n); // for denominators, if needed
1420 exmap srl; // symbol replacement list
1421 auto tmp_n_it = tmp_n.m.begin(), tmp_d_it = tmp_d.m.begin();
1422 for (auto & it : this->m) {
1423 ex nd = it.normal().to_rational(srl).numer_denom();
1424 *tmp_n_it++ = nd.op(0);
1425 *tmp_d_it++ = nd.op(1);
1429 for (unsigned c0=0; c0<n && r0<m-1; ++c0) {
1430 // When trying to find a pivot, we should try a bit harder than expand().
1431 // Searching the first non-zero element in-place here instead of calling
1432 // pivot() allows us to do no more substitutions and back-substitutions
1433 // than are actually necessary.
1436 (tmp_n[indx*n+c0].subs(srl, subs_options::no_pattern).expand().is_zero()))
1439 // all elements in column c0 below row r0 vanish
1445 // Matrix needs pivoting, swap rows r0 and indx of tmp_n and tmp_d.
1447 for (unsigned c=c0; c<n; ++c) {
1448 tmp_n.m[n*indx+c].swap(tmp_n.m[n*r0+c]);
1449 tmp_d.m[n*indx+c].swap(tmp_d.m[n*r0+c]);
1452 for (unsigned r2=r0+1; r2<m; ++r2) {
1453 for (unsigned c=c0+1; c<n; ++c) {
1454 dividend_n = (tmp_n.m[r0*n+c0]*tmp_n.m[r2*n+c]*
1455 tmp_d.m[r2*n+c0]*tmp_d.m[r0*n+c]
1456 -tmp_n.m[r2*n+c0]*tmp_n.m[r0*n+c]*
1457 tmp_d.m[r0*n+c0]*tmp_d.m[r2*n+c]).expand();
1458 dividend_d = (tmp_d.m[r2*n+c0]*tmp_d.m[r0*n+c]*
1459 tmp_d.m[r0*n+c0]*tmp_d.m[r2*n+c]).expand();
1460 bool check = divide(dividend_n, divisor_n,
1461 tmp_n.m[r2*n+c], true);
1462 check &= divide(dividend_d, divisor_d,
1463 tmp_d.m[r2*n+c], true);
1464 GINAC_ASSERT(check);
1466 // fill up left hand side with zeros
1467 for (unsigned c=r0; c<=c0; ++c)
1468 tmp_n.m[r2*n+c] = _ex0;
1470 if (c0<n && r0<m-1) {
1471 // compute next iteration's divisor
1472 divisor_n = tmp_n.m[r0*n+c0].expand();
1473 divisor_d = tmp_d.m[r0*n+c0].expand();
1475 // save space by deleting no longer needed elements
1476 for (unsigned c=0; c<n; ++c) {
1477 tmp_n.m[r0*n+c] = _ex0;
1478 tmp_d.m[r0*n+c] = _ex1;
1485 // clear remaining rows
1486 for (unsigned r=r0+1; r<m; ++r) {
1487 for (unsigned c=0; c<n; ++c)
1488 tmp_n.m[r*n+c] = _ex0;
1491 // repopulate *this matrix:
1492 tmp_n_it = tmp_n.m.begin();
1493 tmp_d_it = tmp_d.m.begin();
1494 for (auto & it : this->m)
1495 it = ((*tmp_n_it++)/(*tmp_d_it++)).subs(srl, subs_options::no_pattern);
1501 /** Partial pivoting method for matrix elimination schemes.
1502 * Usual pivoting (symbolic==false) returns the index to the element with the
1503 * largest absolute value in column ro and swaps the current row with the one
1504 * where the element was found. With (symbolic==true) it does the same thing
1505 * with the first non-zero element.
1507 * @param ro is the row from where to begin
1508 * @param co is the column to be inspected
1509 * @param symbolic signal if we want the first non-zero element to be pivoted
1510 * (true) or the one with the largest absolute value (false).
1511 * @return 0 if no interchange occurred, -1 if all are zero (usually signaling
1512 * a degeneracy) and positive integer k means that rows ro and k were swapped.
1514 int matrix::pivot(unsigned ro, unsigned co, bool symbolic)
1518 // search first non-zero element in column co beginning at row ro
1519 while ((k<row) && (this->m[k*col+co].expand().is_zero()))
1522 // search largest element in column co beginning at row ro
1523 GINAC_ASSERT(is_exactly_a<numeric>(this->m[k*col+co]));
1524 unsigned kmax = k+1;
1525 numeric mmax = abs(ex_to<numeric>(m[kmax*col+co]));
1527 GINAC_ASSERT(is_exactly_a<numeric>(this->m[kmax*col+co]));
1528 numeric tmp = ex_to<numeric>(this->m[kmax*col+co]);
1529 if (abs(tmp) > mmax) {
1535 if (!mmax.is_zero())
1539 // all elements in column co below row ro vanish
1542 // matrix needs no pivoting
1544 // matrix needs pivoting, so swap rows k and ro
1545 ensure_if_modifiable();
1546 for (unsigned c=0; c<col; ++c)
1547 this->m[k*col+c].swap(this->m[ro*col+c]);
1552 /** Function to check that all elements of the matrix are zero.
1554 bool matrix::is_zero_matrix() const
1562 ex lst_to_matrix(const lst & l)
1564 // Find number of rows and columns
1565 size_t rows = l.nops(), cols = 0;
1566 for (auto & itr : l) {
1567 if (!is_a<lst>(itr))
1568 throw (std::invalid_argument("lst_to_matrix: argument must be a list of lists"));
1569 if (itr.nops() > cols)
1573 // Allocate and fill matrix
1574 matrix & M = dynallocate<matrix>(rows, cols);
1577 for (auto & itr : l) {
1579 for (auto & itc : ex_to<lst>(itr)) {
1589 ex diag_matrix(const lst & l)
1591 size_t dim = l.nops();
1593 // Allocate and fill matrix
1594 matrix & M = dynallocate<matrix>(dim, dim);
1597 for (auto & it : l) {
1605 ex diag_matrix(std::initializer_list<ex> l)
1607 size_t dim = l.size();
1609 // Allocate and fill matrix
1610 matrix & M = dynallocate<matrix>(dim, dim);
1613 for (auto & it : l) {
1621 ex unit_matrix(unsigned r, unsigned c)
1623 matrix & Id = dynallocate<matrix>(r, c);
1624 Id.setflag(status_flags::evaluated);
1625 for (unsigned i=0; i<r && i<c; i++)
1631 ex symbolic_matrix(unsigned r, unsigned c, const std::string & base_name, const std::string & tex_base_name)
1633 matrix & M = dynallocate<matrix>(r, c);
1634 M.setflag(status_flags::evaluated);
1636 bool long_format = (r > 10 || c > 10);
1637 bool single_row = (r == 1 || c == 1);
1639 for (unsigned i=0; i<r; i++) {
1640 for (unsigned j=0; j<c; j++) {
1641 std::ostringstream s1, s2;
1643 s2 << tex_base_name << "_{";
1654 s1 << '_' << i << '_' << j;
1655 s2 << i << ';' << j << "}";
1658 s2 << i << j << '}';
1661 M(i, j) = symbol(s1.str(), s2.str());
1668 ex reduced_matrix(const matrix& m, unsigned r, unsigned c)
1670 if (r+1>m.rows() || c+1>m.cols() || m.cols()<2 || m.rows()<2)
1671 throw std::runtime_error("minor_matrix(): index out of bounds");
1673 const unsigned rows = m.rows()-1;
1674 const unsigned cols = m.cols()-1;
1675 matrix & M = dynallocate<matrix>(rows, cols);
1676 M.setflag(status_flags::evaluated);
1688 M(ro2,co2) = m(ro, co);
1699 ex sub_matrix(const matrix&m, unsigned r, unsigned nr, unsigned c, unsigned nc)
1701 if (r+nr>m.rows() || c+nc>m.cols())
1702 throw std::runtime_error("sub_matrix(): index out of bounds");
1704 matrix & M = dynallocate<matrix>(nr, nc);
1705 M.setflag(status_flags::evaluated);
1707 for (unsigned ro=0; ro<nr; ++ro) {
1708 for (unsigned co=0; co<nc; ++co) {
1709 M(ro,co) = m(ro+r,co+c);
1716 } // namespace GiNaC