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 (new matrix(row, col, std::move(m2)))->setflag(status_flags::dynallocated |
249 status_flags::evaluated);
252 ex matrix::subs(const exmap & mp, unsigned options) const
254 exvector m2(row * col);
255 for (unsigned r=0; r<row; ++r)
256 for (unsigned c=0; c<col; ++c)
257 m2[r*col+c] = m[r*col+c].subs(mp, options);
259 return matrix(row, col, std::move(m2)).subs_one_level(mp, options);
262 /** Complex conjugate every matrix entry. */
263 ex matrix::conjugate() const
265 std::unique_ptr<exvector> ev(nullptr);
266 for (auto i=m.begin(); i!=m.end(); ++i) {
267 ex x = i->conjugate();
272 if (are_ex_trivially_equal(x, *i)) {
275 ev.reset(new exvector);
276 ev->reserve(m.size());
277 for (auto j=m.begin(); j!=i; ++j) {
283 return matrix(row, col, std::move(*ev));
288 ex matrix::real_part() const
293 v.push_back(i.real_part());
294 return matrix(row, col, std::move(v));
297 ex matrix::imag_part() const
302 v.push_back(i.imag_part());
303 return matrix(row, col, std::move(v));
308 int matrix::compare_same_type(const basic & other) const
310 GINAC_ASSERT(is_exactly_a<matrix>(other));
311 const matrix &o = static_cast<const matrix &>(other);
313 // compare number of rows
315 return row < o.rows() ? -1 : 1;
317 // compare number of columns
319 return col < o.cols() ? -1 : 1;
321 // equal number of rows and columns, compare individual elements
323 for (unsigned r=0; r<row; ++r) {
324 for (unsigned c=0; c<col; ++c) {
325 cmpval = ((*this)(r,c)).compare(o(r,c));
326 if (cmpval!=0) return cmpval;
329 // all elements are equal => matrices are equal;
333 bool matrix::match_same_type(const basic & other) const
335 GINAC_ASSERT(is_exactly_a<matrix>(other));
336 const matrix & o = static_cast<const matrix &>(other);
338 // The number of rows and columns must be the same. This is necessary to
339 // prevent a 2x3 matrix from matching a 3x2 one.
340 return row == o.rows() && col == o.cols();
343 /** Automatic symbolic evaluation of an indexed matrix. */
344 ex matrix::eval_indexed(const basic & i) const
346 GINAC_ASSERT(is_a<indexed>(i));
347 GINAC_ASSERT(is_a<matrix>(i.op(0)));
349 bool all_indices_unsigned = static_cast<const indexed &>(i).all_index_values_are(info_flags::nonnegint);
354 // One index, must be one-dimensional vector
355 if (row != 1 && col != 1)
356 throw (std::runtime_error("matrix::eval_indexed(): vector must have exactly 1 index"));
358 const idx & i1 = ex_to<idx>(i.op(1));
363 if (!i1.get_dim().is_equal(row))
364 throw (std::runtime_error("matrix::eval_indexed(): dimension of index must match number of vector elements"));
366 // Index numeric -> return vector element
367 if (all_indices_unsigned) {
368 unsigned n1 = ex_to<numeric>(i1.get_value()).to_int();
370 throw (std::runtime_error("matrix::eval_indexed(): value of index exceeds number of vector elements"));
371 return (*this)(n1, 0);
377 if (!i1.get_dim().is_equal(col))
378 throw (std::runtime_error("matrix::eval_indexed(): dimension of index must match number of vector elements"));
380 // Index numeric -> return vector element
381 if (all_indices_unsigned) {
382 unsigned n1 = ex_to<numeric>(i1.get_value()).to_int();
384 throw (std::runtime_error("matrix::eval_indexed(): value of index exceeds number of vector elements"));
385 return (*this)(0, n1);
389 } else if (i.nops() == 3) {
392 const idx & i1 = ex_to<idx>(i.op(1));
393 const idx & i2 = ex_to<idx>(i.op(2));
395 if (!i1.get_dim().is_equal(row))
396 throw (std::runtime_error("matrix::eval_indexed(): dimension of first index must match number of rows"));
397 if (!i2.get_dim().is_equal(col))
398 throw (std::runtime_error("matrix::eval_indexed(): dimension of second index must match number of columns"));
400 // Pair of dummy indices -> compute trace
401 if (is_dummy_pair(i1, i2))
404 // Both indices numeric -> return matrix element
405 if (all_indices_unsigned) {
406 unsigned n1 = ex_to<numeric>(i1.get_value()).to_int(), n2 = ex_to<numeric>(i2.get_value()).to_int();
408 throw (std::runtime_error("matrix::eval_indexed(): value of first index exceeds number of rows"));
410 throw (std::runtime_error("matrix::eval_indexed(): value of second index exceeds number of columns"));
411 return (*this)(n1, n2);
415 throw (std::runtime_error("matrix::eval_indexed(): matrix must have exactly 2 indices"));
420 /** Sum of two indexed matrices. */
421 ex matrix::add_indexed(const ex & self, const ex & other) const
423 GINAC_ASSERT(is_a<indexed>(self));
424 GINAC_ASSERT(is_a<matrix>(self.op(0)));
425 GINAC_ASSERT(is_a<indexed>(other));
426 GINAC_ASSERT(self.nops() == 2 || self.nops() == 3);
428 // Only add two matrices
429 if (is_a<matrix>(other.op(0))) {
430 GINAC_ASSERT(other.nops() == 2 || other.nops() == 3);
432 const matrix &self_matrix = ex_to<matrix>(self.op(0));
433 const matrix &other_matrix = ex_to<matrix>(other.op(0));
435 if (self.nops() == 2 && other.nops() == 2) { // vector + vector
437 if (self_matrix.row == other_matrix.row)
438 return indexed(self_matrix.add(other_matrix), self.op(1));
439 else if (self_matrix.row == other_matrix.col)
440 return indexed(self_matrix.add(other_matrix.transpose()), self.op(1));
442 } else if (self.nops() == 3 && other.nops() == 3) { // matrix + matrix
444 if (self.op(1).is_equal(other.op(1)) && self.op(2).is_equal(other.op(2)))
445 return indexed(self_matrix.add(other_matrix), self.op(1), self.op(2));
446 else if (self.op(1).is_equal(other.op(2)) && self.op(2).is_equal(other.op(1)))
447 return indexed(self_matrix.add(other_matrix.transpose()), self.op(1), self.op(2));
452 // Don't know what to do, return unevaluated sum
456 /** Product of an indexed matrix with a number. */
457 ex matrix::scalar_mul_indexed(const ex & self, const numeric & other) const
459 GINAC_ASSERT(is_a<indexed>(self));
460 GINAC_ASSERT(is_a<matrix>(self.op(0)));
461 GINAC_ASSERT(self.nops() == 2 || self.nops() == 3);
463 const matrix &self_matrix = ex_to<matrix>(self.op(0));
465 if (self.nops() == 2)
466 return indexed(self_matrix.mul(other), self.op(1));
467 else // self.nops() == 3
468 return indexed(self_matrix.mul(other), self.op(1), self.op(2));
471 /** Contraction of an indexed matrix with something else. */
472 bool matrix::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
474 GINAC_ASSERT(is_a<indexed>(*self));
475 GINAC_ASSERT(is_a<indexed>(*other));
476 GINAC_ASSERT(self->nops() == 2 || self->nops() == 3);
477 GINAC_ASSERT(is_a<matrix>(self->op(0)));
479 // Only contract with other matrices
480 if (!is_a<matrix>(other->op(0)))
483 GINAC_ASSERT(other->nops() == 2 || other->nops() == 3);
485 const matrix &self_matrix = ex_to<matrix>(self->op(0));
486 const matrix &other_matrix = ex_to<matrix>(other->op(0));
488 if (self->nops() == 2) {
490 if (other->nops() == 2) { // vector * vector (scalar product)
492 if (self_matrix.col == 1) {
493 if (other_matrix.col == 1) {
494 // Column vector * column vector, transpose first vector
495 *self = self_matrix.transpose().mul(other_matrix)(0, 0);
497 // Column vector * row vector, swap factors
498 *self = other_matrix.mul(self_matrix)(0, 0);
501 if (other_matrix.col == 1) {
502 // Row vector * column vector, perfect
503 *self = self_matrix.mul(other_matrix)(0, 0);
505 // Row vector * row vector, transpose second vector
506 *self = self_matrix.mul(other_matrix.transpose())(0, 0);
512 } else { // vector * matrix
514 // B_i * A_ij = (B*A)_j (B is row vector)
515 if (is_dummy_pair(self->op(1), other->op(1))) {
516 if (self_matrix.row == 1)
517 *self = indexed(self_matrix.mul(other_matrix), other->op(2));
519 *self = indexed(self_matrix.transpose().mul(other_matrix), other->op(2));
524 // B_j * A_ij = (A*B)_i (B is column vector)
525 if (is_dummy_pair(self->op(1), other->op(2))) {
526 if (self_matrix.col == 1)
527 *self = indexed(other_matrix.mul(self_matrix), other->op(1));
529 *self = indexed(other_matrix.mul(self_matrix.transpose()), other->op(1));
535 } else if (other->nops() == 3) { // matrix * matrix
537 // A_ij * B_jk = (A*B)_ik
538 if (is_dummy_pair(self->op(2), other->op(1))) {
539 *self = indexed(self_matrix.mul(other_matrix), self->op(1), other->op(2));
544 // A_ij * B_kj = (A*Btrans)_ik
545 if (is_dummy_pair(self->op(2), other->op(2))) {
546 *self = indexed(self_matrix.mul(other_matrix.transpose()), self->op(1), other->op(1));
551 // A_ji * B_jk = (Atrans*B)_ik
552 if (is_dummy_pair(self->op(1), other->op(1))) {
553 *self = indexed(self_matrix.transpose().mul(other_matrix), self->op(2), other->op(2));
558 // A_ji * B_kj = (B*A)_ki
559 if (is_dummy_pair(self->op(1), other->op(2))) {
560 *self = indexed(other_matrix.mul(self_matrix), other->op(1), self->op(2));
571 // non-virtual functions in this class
578 * @exception logic_error (incompatible matrices) */
579 matrix matrix::add(const matrix & other) const
581 if (col != other.col || row != other.row)
582 throw std::logic_error("matrix::add(): incompatible matrices");
584 exvector sum(this->m);
585 auto ci = other.m.begin();
589 return matrix(row, col, std::move(sum));
593 /** Difference of matrices.
595 * @exception logic_error (incompatible matrices) */
596 matrix matrix::sub(const matrix & other) const
598 if (col != other.col || row != other.row)
599 throw std::logic_error("matrix::sub(): incompatible matrices");
601 exvector dif(this->m);
602 auto ci = other.m.begin();
606 return matrix(row, col, std::move(dif));
610 /** Product of matrices.
612 * @exception logic_error (incompatible matrices) */
613 matrix matrix::mul(const matrix & other) const
615 if (this->cols() != other.rows())
616 throw std::logic_error("matrix::mul(): incompatible matrices");
618 exvector prod(this->rows()*other.cols());
620 for (unsigned r1=0; r1<this->rows(); ++r1) {
621 for (unsigned c=0; c<this->cols(); ++c) {
622 // Quick test: can we shortcut?
623 if (m[r1*col+c].is_zero())
625 for (unsigned r2=0; r2<other.cols(); ++r2)
626 prod[r1*other.col+r2] += (m[r1*col+c] * other.m[c*other.col+r2]);
629 return matrix(row, other.col, std::move(prod));
633 /** Product of matrix and scalar. */
634 matrix matrix::mul(const numeric & other) const
636 exvector prod(row * col);
638 for (unsigned r=0; r<row; ++r)
639 for (unsigned c=0; c<col; ++c)
640 prod[r*col+c] = m[r*col+c] * other;
642 return matrix(row, col, std::move(prod));
646 /** Product of matrix and scalar expression. */
647 matrix matrix::mul_scalar(const ex & other) const
649 if (other.return_type() != return_types::commutative)
650 throw std::runtime_error("matrix::mul_scalar(): non-commutative scalar");
652 exvector prod(row * col);
654 for (unsigned r=0; r<row; ++r)
655 for (unsigned c=0; c<col; ++c)
656 prod[r*col+c] = m[r*col+c] * other;
658 return matrix(row, col, std::move(prod));
662 /** Power of a matrix. Currently handles integer exponents only. */
663 matrix matrix::pow(const ex & expn) const
666 throw (std::logic_error("matrix::pow(): matrix not square"));
668 if (is_exactly_a<numeric>(expn)) {
669 // Integer cases are computed by successive multiplication, using the
670 // obvious shortcut of storing temporaries, like A^4 == (A*A)*(A*A).
671 if (expn.info(info_flags::integer)) {
672 numeric b = ex_to<numeric>(expn);
674 if (expn.info(info_flags::negative)) {
681 for (unsigned r=0; r<row; ++r)
685 // This loop computes the representation of b in base 2 from right
686 // to left and multiplies the factors whenever needed. Note
687 // that this is not entirely optimal but close to optimal and
688 // "better" algorithms are much harder to implement. (See Knuth,
689 // TAoCP2, section "Evaluation of Powers" for a good discussion.)
690 while (b!=*_num1_p) {
695 b /= *_num2_p; // still integer.
701 throw (std::runtime_error("matrix::pow(): don't know how to handle exponent"));
705 /** operator() to access elements for reading.
707 * @param ro row of element
708 * @param co column of element
709 * @exception range_error (index out of range) */
710 const ex & matrix::operator() (unsigned ro, unsigned co) const
712 if (ro>=row || co>=col)
713 throw (std::range_error("matrix::operator(): index out of range"));
719 /** operator() to access elements for writing.
721 * @param ro row of element
722 * @param co column of element
723 * @exception range_error (index out of range) */
724 ex & matrix::operator() (unsigned ro, unsigned co)
726 if (ro>=row || co>=col)
727 throw (std::range_error("matrix::operator(): index out of range"));
729 ensure_if_modifiable();
734 /** Transposed of an m x n matrix, producing a new n x m matrix object that
735 * represents the transposed. */
736 matrix matrix::transpose() const
738 exvector trans(this->cols()*this->rows());
740 for (unsigned r=0; r<this->cols(); ++r)
741 for (unsigned c=0; c<this->rows(); ++c)
742 trans[r*this->rows()+c] = m[c*this->cols()+r];
744 return matrix(this->cols(), this->rows(), std::move(trans));
747 /** Determinant of square matrix. This routine doesn't actually calculate the
748 * determinant, it only implements some heuristics about which algorithm to
749 * run. If all the elements of the matrix are elements of an integral domain
750 * the determinant is also in that integral domain and the result is expanded
751 * only. If one or more elements are from a quotient field the determinant is
752 * usually also in that quotient field and the result is normalized before it
753 * is returned. This implies that the determinant of the symbolic 2x2 matrix
754 * [[a/(a-b),1],[b/(a-b),1]] is returned as unity. (In this respect, it
755 * behaves like MapleV and unlike Mathematica.)
757 * @param algo allows to chose an algorithm
758 * @return the determinant as a new expression
759 * @exception logic_error (matrix not square)
760 * @see determinant_algo */
761 ex matrix::determinant(unsigned algo) const
764 throw (std::logic_error("matrix::determinant(): matrix not square"));
765 GINAC_ASSERT(row*col==m.capacity());
767 // Gather some statistical information about this matrix:
768 bool numeric_flag = true;
769 bool normal_flag = false;
770 unsigned sparse_count = 0; // counts non-zero elements
772 if (!r.info(info_flags::numeric))
773 numeric_flag = false;
774 exmap srl; // symbol replacement list
775 ex rtest = r.to_rational(srl);
776 if (!rtest.is_zero())
778 if (!rtest.info(info_flags::crational_polynomial) &&
779 rtest.info(info_flags::rational_function))
783 // Here is the heuristics in case this routine has to decide:
784 if (algo == determinant_algo::automatic) {
785 // Minor expansion is generally a good guess:
786 algo = determinant_algo::laplace;
787 // Does anybody know when a matrix is really sparse?
788 // Maybe <~row/2.236 nonzero elements average in a row?
789 if (row>3 && 5*sparse_count<=row*col)
790 algo = determinant_algo::bareiss;
791 // Purely numeric matrix can be handled by Gauss elimination.
792 // This overrides any prior decisions.
794 algo = determinant_algo::gauss;
797 // Trap the trivial case here, since some algorithms don't like it
799 // for consistency with non-trivial determinants...
801 return m[0].normal();
803 return m[0].expand();
806 // Compute the determinant
808 case determinant_algo::gauss: {
811 int sign = tmp.gauss_elimination(true);
812 for (unsigned d=0; d<row; ++d)
813 det *= tmp.m[d*col+d];
815 return (sign*det).normal();
817 return (sign*det).normal().expand();
819 case determinant_algo::bareiss: {
822 sign = tmp.fraction_free_elimination(true);
824 return (sign*tmp.m[row*col-1]).normal();
826 return (sign*tmp.m[row*col-1]).expand();
828 case determinant_algo::divfree: {
831 sign = tmp.division_free_elimination(true);
834 ex det = tmp.m[row*col-1];
835 // factor out accumulated bogus slag
836 for (unsigned d=0; d<row-2; ++d)
837 for (unsigned j=0; j<row-d-2; ++j)
838 det = (det/tmp.m[d*col+d]).normal();
841 case determinant_algo::laplace:
843 // This is the minor expansion scheme. We always develop such
844 // that the smallest minors (i.e, the trivial 1x1 ones) are on the
845 // rightmost column. For this to be efficient, empirical tests
846 // have shown that the emptiest columns (i.e. the ones with most
847 // zeros) should be the ones on the right hand side -- although
848 // this might seem counter-intuitive (and in contradiction to some
849 // literature like the FORM manual). Please go ahead and test it
850 // if you don't believe me! Therefore we presort the columns of
852 typedef std::pair<unsigned,unsigned> uintpair;
853 std::vector<uintpair> c_zeros; // number of zeros in column
854 for (unsigned c=0; c<col; ++c) {
856 for (unsigned r=0; r<row; ++r)
857 if (m[r*col+c].is_zero())
859 c_zeros.push_back(uintpair(acc,c));
861 std::sort(c_zeros.begin(),c_zeros.end());
862 std::vector<unsigned> pre_sort;
863 for (auto & i : c_zeros)
864 pre_sort.push_back(i.second);
865 std::vector<unsigned> pre_sort_test(pre_sort); // permutation_sign() modifies the vector so we make a copy here
866 int sign = permutation_sign(pre_sort_test.begin(), pre_sort_test.end());
867 exvector result(row*col); // represents sorted matrix
869 for (auto & it : pre_sort) {
870 for (unsigned r=0; r<row; ++r)
871 result[r*col+c] = m[r*col+it];
876 return (sign*matrix(row, col, std::move(result)).determinant_minor()).normal();
878 return sign*matrix(row, col, std::move(result)).determinant_minor();
884 /** Trace of a matrix. The result is normalized if it is in some quotient
885 * field and expanded only otherwise. This implies that the trace of the
886 * symbolic 2x2 matrix [[a/(a-b),x],[y,b/(b-a)]] is recognized to be unity.
888 * @return the sum of diagonal elements
889 * @exception logic_error (matrix not square) */
890 ex matrix::trace() const
893 throw (std::logic_error("matrix::trace(): matrix not square"));
896 for (unsigned r=0; r<col; ++r)
899 if (tr.info(info_flags::rational_function) &&
900 !tr.info(info_flags::crational_polynomial))
907 /** Characteristic Polynomial. Following mathematica notation the
908 * characteristic polynomial of a matrix M is defined as the determinant of
909 * (M - lambda * 1) where 1 stands for the unit matrix of the same dimension
910 * as M. Note that some CASs define it with a sign inside the determinant
911 * which gives rise to an overall sign if the dimension is odd. This method
912 * returns the characteristic polynomial collected in powers of lambda as a
915 * @return characteristic polynomial as new expression
916 * @exception logic_error (matrix not square)
917 * @see matrix::determinant() */
918 ex matrix::charpoly(const ex & lambda) const
921 throw (std::logic_error("matrix::charpoly(): matrix not square"));
923 bool numeric_flag = true;
925 if (!r.info(info_flags::numeric)) {
926 numeric_flag = false;
931 // The pure numeric case is traditionally rather common. Hence, it is
932 // trapped and we use Leverrier's algorithm which goes as row^3 for
933 // every coefficient. The expensive part is the matrix multiplication.
938 ex poly = power(lambda, row) - c*power(lambda, row-1);
939 for (unsigned i=1; i<row; ++i) {
940 for (unsigned j=0; j<row; ++j)
943 c = B.trace() / ex(i+1);
944 poly -= c*power(lambda, row-i-1);
954 for (unsigned r=0; r<col; ++r)
955 M.m[r*col+r] -= lambda;
957 return M.determinant().collect(lambda);
962 /** Inverse of this matrix.
964 * @return the inverted matrix
965 * @exception logic_error (matrix not square)
966 * @exception runtime_error (singular matrix) */
967 matrix matrix::inverse() const
970 throw (std::logic_error("matrix::inverse(): matrix not square"));
972 // This routine actually doesn't do anything fancy at all. We compute the
973 // inverse of the matrix A by solving the system A * A^{-1} == Id.
975 // First populate the identity matrix supposed to become the right hand side.
976 matrix identity(row,col);
977 for (unsigned i=0; i<row; ++i)
978 identity(i,i) = _ex1;
980 // Populate a dummy matrix of variables, just because of compatibility with
981 // matrix::solve() which wants this (for compatibility with under-determined
982 // systems of equations).
983 matrix vars(row,col);
984 for (unsigned r=0; r<row; ++r)
985 for (unsigned c=0; c<col; ++c)
986 vars(r,c) = symbol();
990 sol = this->solve(vars,identity);
991 } catch (const std::runtime_error & e) {
992 if (e.what()==std::string("matrix::solve(): inconsistent linear system"))
993 throw (std::runtime_error("matrix::inverse(): singular matrix"));
1001 /** Solve a linear system consisting of a m x n matrix and a m x p right hand
1002 * side by applying an elimination scheme to the augmented matrix.
1004 * @param vars n x p matrix, all elements must be symbols
1005 * @param rhs m x p matrix
1006 * @param algo selects the solving algorithm
1007 * @return n x p solution matrix
1008 * @exception logic_error (incompatible matrices)
1009 * @exception invalid_argument (1st argument must be matrix of symbols)
1010 * @exception runtime_error (inconsistent linear system)
1011 * @see solve_algo */
1012 matrix matrix::solve(const matrix & vars,
1014 unsigned algo) const
1016 const unsigned m = this->rows();
1017 const unsigned n = this->cols();
1018 const unsigned p = rhs.cols();
1021 if ((rhs.rows() != m) || (vars.rows() != n) || (vars.col != p))
1022 throw (std::logic_error("matrix::solve(): incompatible matrices"));
1023 for (unsigned ro=0; ro<n; ++ro)
1024 for (unsigned co=0; co<p; ++co)
1025 if (!vars(ro,co).info(info_flags::symbol))
1026 throw (std::invalid_argument("matrix::solve(): 1st argument must be matrix of symbols"));
1028 // build the augmented matrix of *this with rhs attached to the right
1030 for (unsigned r=0; r<m; ++r) {
1031 for (unsigned c=0; c<n; ++c)
1032 aug.m[r*(n+p)+c] = this->m[r*n+c];
1033 for (unsigned c=0; c<p; ++c)
1034 aug.m[r*(n+p)+c+n] = rhs.m[r*p+c];
1037 // Gather some statistical information about the augmented matrix:
1038 bool numeric_flag = true;
1039 for (auto & r : aug.m) {
1040 if (!r.info(info_flags::numeric)) {
1041 numeric_flag = false;
1046 // Here is the heuristics in case this routine has to decide:
1047 if (algo == solve_algo::automatic) {
1048 // Bareiss (fraction-free) elimination is generally a good guess:
1049 algo = solve_algo::bareiss;
1050 // For m<3, Bareiss elimination is equivalent to division free
1051 // elimination but has more logistic overhead
1053 algo = solve_algo::divfree;
1054 // This overrides any prior decisions.
1056 algo = solve_algo::gauss;
1059 // Eliminate the augmented matrix:
1061 case solve_algo::gauss:
1062 aug.gauss_elimination();
1064 case solve_algo::divfree:
1065 aug.division_free_elimination();
1067 case solve_algo::bareiss:
1069 aug.fraction_free_elimination();
1072 // assemble the solution matrix:
1074 for (unsigned co=0; co<p; ++co) {
1075 unsigned last_assigned_sol = n+1;
1076 for (int r=m-1; r>=0; --r) {
1077 unsigned fnz = 1; // first non-zero in row
1078 while ((fnz<=n) && (aug.m[r*(n+p)+(fnz-1)].is_zero()))
1081 // row consists only of zeros, corresponding rhs must be 0, too
1082 if (!aug.m[r*(n+p)+n+co].is_zero()) {
1083 throw (std::runtime_error("matrix::solve(): inconsistent linear system"));
1086 // assign solutions for vars between fnz+1 and
1087 // last_assigned_sol-1: free parameters
1088 for (unsigned c=fnz; c<last_assigned_sol-1; ++c)
1089 sol(c,co) = vars.m[c*p+co];
1090 ex e = aug.m[r*(n+p)+n+co];
1091 for (unsigned c=fnz; c<n; ++c)
1092 e -= aug.m[r*(n+p)+c]*sol.m[c*p+co];
1093 sol(fnz-1,co) = (e/(aug.m[r*(n+p)+(fnz-1)])).normal();
1094 last_assigned_sol = fnz;
1097 // assign solutions for vars between 1 and
1098 // last_assigned_sol-1: free parameters
1099 for (unsigned ro=0; ro<last_assigned_sol-1; ++ro)
1100 sol(ro,co) = vars(ro,co);
1107 /** Compute the rank of this matrix. */
1108 unsigned matrix::rank() const
1111 // Transform this matrix into upper echelon form and then count the
1112 // number of non-zero rows.
1114 GINAC_ASSERT(row*col==m.capacity());
1116 // Actually, any elimination scheme will do since we are only
1117 // interested in the echelon matrix' zeros.
1118 matrix to_eliminate = *this;
1119 to_eliminate.fraction_free_elimination();
1121 unsigned r = row*col; // index of last non-zero element
1123 if (!to_eliminate.m[r].is_zero())
1132 /** Recursive determinant for small matrices having at least one symbolic
1133 * entry. The basic algorithm, known as Laplace-expansion, is enhanced by
1134 * some bookkeeping to avoid calculation of the same submatrices ("minors")
1135 * more than once. According to W.M.Gentleman and S.C.Johnson this algorithm
1136 * is better than elimination schemes for matrices of sparse multivariate
1137 * polynomials and also for matrices of dense univariate polynomials if the
1138 * matrix' dimension is larger than 7.
1140 * @return the determinant as a new expression (in expanded form)
1141 * @see matrix::determinant() */
1142 ex matrix::determinant_minor() const
1144 // for small matrices the algorithm does not make any sense:
1145 const unsigned n = this->cols();
1147 return m[0].expand();
1149 return (m[0]*m[3]-m[2]*m[1]).expand();
1151 return (m[0]*m[4]*m[8]-m[0]*m[5]*m[7]-
1152 m[1]*m[3]*m[8]+m[2]*m[3]*m[7]+
1153 m[1]*m[5]*m[6]-m[2]*m[4]*m[6]).expand();
1155 // This algorithm can best be understood by looking at a naive
1156 // implementation of Laplace-expansion, like this one:
1158 // matrix minorM(this->rows()-1,this->cols()-1);
1159 // for (unsigned r1=0; r1<this->rows(); ++r1) {
1160 // // shortcut if element(r1,0) vanishes
1161 // if (m[r1*col].is_zero())
1163 // // assemble the minor matrix
1164 // for (unsigned r=0; r<minorM.rows(); ++r) {
1165 // for (unsigned c=0; c<minorM.cols(); ++c) {
1167 // minorM(r,c) = m[r*col+c+1];
1169 // minorM(r,c) = m[(r+1)*col+c+1];
1172 // // recurse down and care for sign:
1174 // det -= m[r1*col] * minorM.determinant_minor();
1176 // det += m[r1*col] * minorM.determinant_minor();
1178 // return det.expand();
1179 // What happens is that while proceeding down many of the minors are
1180 // computed more than once. In particular, there are binomial(n,k)
1181 // kxk minors and each one is computed factorial(n-k) times. Therefore
1182 // it is reasonable to store the results of the minors. We proceed from
1183 // right to left. At each column c we only need to retrieve the minors
1184 // calculated in step c-1. We therefore only have to store at most
1185 // 2*binomial(n,n/2) minors.
1187 // Unique flipper counter for partitioning into minors
1188 std::vector<unsigned> Pkey;
1190 // key for minor determinant (a subpartition of Pkey)
1191 std::vector<unsigned> Mkey;
1193 // we store our subminors in maps, keys being the rows they arise from
1194 typedef std::map<std::vector<unsigned>,class ex> Rmap;
1195 typedef std::map<std::vector<unsigned>,class ex>::value_type Rmap_value;
1199 // initialize A with last column:
1200 for (unsigned r=0; r<n; ++r) {
1201 Pkey.erase(Pkey.begin(),Pkey.end());
1203 A.insert(Rmap_value(Pkey,m[n*(r+1)-1]));
1205 // proceed from right to left through matrix
1206 for (int c=n-2; c>=0; --c) {
1207 Pkey.erase(Pkey.begin(),Pkey.end()); // don't change capacity
1208 Mkey.erase(Mkey.begin(),Mkey.end());
1209 for (unsigned i=0; i<n-c; ++i)
1211 unsigned fc = 0; // controls logic for our strange flipper counter
1214 for (unsigned r=0; r<n-c; ++r) {
1215 // maybe there is nothing to do?
1216 if (m[Pkey[r]*n+c].is_zero())
1218 // create the sorted key for all possible minors
1219 Mkey.erase(Mkey.begin(),Mkey.end());
1220 for (unsigned i=0; i<n-c; ++i)
1222 Mkey.push_back(Pkey[i]);
1223 // Fetch the minors and compute the new determinant
1225 det -= m[Pkey[r]*n+c]*A[Mkey];
1227 det += m[Pkey[r]*n+c]*A[Mkey];
1229 // prevent build-up of deep nesting of expressions saves time:
1231 // store the new determinant at its place in B:
1233 B.insert(Rmap_value(Pkey,det));
1234 // increment our strange flipper counter
1235 for (fc=n-c; fc>0; --fc) {
1237 if (Pkey[fc-1]<fc+c)
1241 for (unsigned j=fc; j<n-c; ++j)
1242 Pkey[j] = Pkey[j-1]+1;
1244 // next column, clear B and change the role of A and B:
1252 /** Perform the steps of an ordinary Gaussian elimination to bring the m x n
1253 * matrix into an upper echelon form. The algorithm is ok for matrices
1254 * with numeric coefficients but quite unsuited for symbolic matrices.
1256 * @param det may be set to true to save a lot of space if one is only
1257 * interested in the diagonal elements (i.e. for calculating determinants).
1258 * The others are set to zero in this case.
1259 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1260 * number of rows was swapped and 0 if the matrix is singular. */
1261 int matrix::gauss_elimination(const bool det)
1263 ensure_if_modifiable();
1264 const unsigned m = this->rows();
1265 const unsigned n = this->cols();
1266 GINAC_ASSERT(!det || n==m);
1270 for (unsigned c0=0; c0<n && r0<m-1; ++c0) {
1271 int indx = pivot(r0, c0, true);
1275 return 0; // leaves *this in a messy state
1280 for (unsigned r2=r0+1; r2<m; ++r2) {
1281 if (!this->m[r2*n+c0].is_zero()) {
1282 // yes, there is something to do in this row
1283 ex piv = this->m[r2*n+c0] / this->m[r0*n+c0];
1284 for (unsigned c=c0+1; c<n; ++c) {
1285 this->m[r2*n+c] -= piv * this->m[r0*n+c];
1286 if (!this->m[r2*n+c].info(info_flags::numeric))
1287 this->m[r2*n+c] = this->m[r2*n+c].normal();
1290 // fill up left hand side with zeros
1291 for (unsigned c=r0; c<=c0; ++c)
1292 this->m[r2*n+c] = _ex0;
1295 // save space by deleting no longer needed elements
1296 for (unsigned c=r0+1; c<n; ++c)
1297 this->m[r0*n+c] = _ex0;
1302 // clear remaining rows
1303 for (unsigned r=r0+1; r<m; ++r) {
1304 for (unsigned c=0; c<n; ++c)
1305 this->m[r*n+c] = _ex0;
1312 /** Perform the steps of division free elimination to bring the m x n matrix
1313 * into an upper echelon form.
1315 * @param det may be set to true to save a lot of space if one is only
1316 * interested in the diagonal elements (i.e. for calculating determinants).
1317 * The others are set to zero in this case.
1318 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1319 * number of rows was swapped and 0 if the matrix is singular. */
1320 int matrix::division_free_elimination(const bool det)
1322 ensure_if_modifiable();
1323 const unsigned m = this->rows();
1324 const unsigned n = this->cols();
1325 GINAC_ASSERT(!det || n==m);
1329 for (unsigned c0=0; c0<n && r0<m-1; ++c0) {
1330 int indx = pivot(r0, c0, true);
1334 return 0; // leaves *this in a messy state
1339 for (unsigned r2=r0+1; r2<m; ++r2) {
1340 for (unsigned c=c0+1; c<n; ++c)
1341 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();
1342 // fill up left hand side with zeros
1343 for (unsigned c=r0; c<=c0; ++c)
1344 this->m[r2*n+c] = _ex0;
1347 // save space by deleting no longer needed elements
1348 for (unsigned c=r0+1; c<n; ++c)
1349 this->m[r0*n+c] = _ex0;
1354 // clear remaining rows
1355 for (unsigned r=r0+1; r<m; ++r) {
1356 for (unsigned c=0; c<n; ++c)
1357 this->m[r*n+c] = _ex0;
1364 /** Perform the steps of Bareiss' one-step fraction free elimination to bring
1365 * the matrix into an upper echelon form. Fraction free elimination means
1366 * that divide is used straightforwardly, without computing GCDs first. This
1367 * is possible, since we know the divisor at each step.
1369 * @param det may be set to true to save a lot of space if one is only
1370 * interested in the last element (i.e. for calculating determinants). The
1371 * others are set to zero in this case.
1372 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1373 * number of rows was swapped and 0 if the matrix is singular. */
1374 int matrix::fraction_free_elimination(const bool det)
1377 // (single-step fraction free elimination scheme, already known to Jordan)
1379 // Usual division-free elimination sets m[0](r,c) = m(r,c) and then sets
1380 // m[k+1](r,c) = m[k](k,k) * m[k](r,c) - m[k](r,k) * m[k](k,c).
1382 // Bareiss (fraction-free) elimination in addition divides that element
1383 // by m[k-1](k-1,k-1) for k>1, where it can be shown by means of the
1384 // Sylvester identity that this really divides m[k+1](r,c).
1386 // We also allow rational functions where the original prove still holds.
1387 // However, we must care for numerator and denominator separately and
1388 // "manually" work in the integral domains because of subtle cancellations
1389 // (see below). This blows up the bookkeeping a bit and the formula has
1390 // to be modified to expand like this (N{x} stands for numerator of x,
1391 // D{x} for denominator of x):
1392 // 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)}
1393 // -N{m[k](r,k)}*N{m[k](k,c)}*D{m[k](k,k)}*D{m[k](r,c)}
1394 // 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)}
1395 // where for k>1 we now divide N{m[k+1](r,c)} by
1396 // N{m[k-1](k-1,k-1)}
1397 // and D{m[k+1](r,c)} by
1398 // D{m[k-1](k-1,k-1)}.
1400 ensure_if_modifiable();
1401 const unsigned m = this->rows();
1402 const unsigned n = this->cols();
1403 GINAC_ASSERT(!det || n==m);
1412 // We populate temporary matrices to subsequently operate on. There is
1413 // one holding numerators and another holding denominators of entries.
1414 // This is a must since the evaluator (or even earlier mul's constructor)
1415 // might cancel some trivial element which causes divide() to fail. The
1416 // elements are normalized first (yes, even though this algorithm doesn't
1417 // need GCDs) since the elements of *this might be unnormalized, which
1418 // makes things more complicated than they need to be.
1419 matrix tmp_n(*this);
1420 matrix tmp_d(m,n); // for denominators, if needed
1421 exmap srl; // symbol replacement list
1422 auto tmp_n_it = tmp_n.m.begin(), tmp_d_it = tmp_d.m.begin();
1423 for (auto & it : this->m) {
1424 ex nd = it.normal().to_rational(srl).numer_denom();
1425 *tmp_n_it++ = nd.op(0);
1426 *tmp_d_it++ = nd.op(1);
1430 for (unsigned c0=0; c0<n && r0<m-1; ++c0) {
1431 // When trying to find a pivot, we should try a bit harder than expand().
1432 // Searching the first non-zero element in-place here instead of calling
1433 // pivot() allows us to do no more substitutions and back-substitutions
1434 // than are actually necessary.
1437 (tmp_n[indx*n+c0].subs(srl, subs_options::no_pattern).expand().is_zero()))
1440 // all elements in column c0 below row r0 vanish
1446 // Matrix needs pivoting, swap rows r0 and indx of tmp_n and tmp_d.
1448 for (unsigned c=c0; c<n; ++c) {
1449 tmp_n.m[n*indx+c].swap(tmp_n.m[n*r0+c]);
1450 tmp_d.m[n*indx+c].swap(tmp_d.m[n*r0+c]);
1453 for (unsigned r2=r0+1; r2<m; ++r2) {
1454 for (unsigned c=c0+1; c<n; ++c) {
1455 dividend_n = (tmp_n.m[r0*n+c0]*tmp_n.m[r2*n+c]*
1456 tmp_d.m[r2*n+c0]*tmp_d.m[r0*n+c]
1457 -tmp_n.m[r2*n+c0]*tmp_n.m[r0*n+c]*
1458 tmp_d.m[r0*n+c0]*tmp_d.m[r2*n+c]).expand();
1459 dividend_d = (tmp_d.m[r2*n+c0]*tmp_d.m[r0*n+c]*
1460 tmp_d.m[r0*n+c0]*tmp_d.m[r2*n+c]).expand();
1461 bool check = divide(dividend_n, divisor_n,
1462 tmp_n.m[r2*n+c], true);
1463 check &= divide(dividend_d, divisor_d,
1464 tmp_d.m[r2*n+c], true);
1465 GINAC_ASSERT(check);
1467 // fill up left hand side with zeros
1468 for (unsigned c=r0; c<=c0; ++c)
1469 tmp_n.m[r2*n+c] = _ex0;
1471 if (c0<n && r0<m-1) {
1472 // compute next iteration's divisor
1473 divisor_n = tmp_n.m[r0*n+c0].expand();
1474 divisor_d = tmp_d.m[r0*n+c0].expand();
1476 // save space by deleting no longer needed elements
1477 for (unsigned c=0; c<n; ++c) {
1478 tmp_n.m[r0*n+c] = _ex0;
1479 tmp_d.m[r0*n+c] = _ex1;
1486 // clear remaining rows
1487 for (unsigned r=r0+1; r<m; ++r) {
1488 for (unsigned c=0; c<n; ++c)
1489 tmp_n.m[r*n+c] = _ex0;
1492 // repopulate *this matrix:
1493 tmp_n_it = tmp_n.m.begin();
1494 tmp_d_it = tmp_d.m.begin();
1495 for (auto & it : this->m)
1496 it = ((*tmp_n_it++)/(*tmp_d_it++)).subs(srl, subs_options::no_pattern);
1502 /** Partial pivoting method for matrix elimination schemes.
1503 * Usual pivoting (symbolic==false) returns the index to the element with the
1504 * largest absolute value in column ro and swaps the current row with the one
1505 * where the element was found. With (symbolic==true) it does the same thing
1506 * with the first non-zero element.
1508 * @param ro is the row from where to begin
1509 * @param co is the column to be inspected
1510 * @param symbolic signal if we want the first non-zero element to be pivoted
1511 * (true) or the one with the largest absolute value (false).
1512 * @return 0 if no interchange occurred, -1 if all are zero (usually signaling
1513 * a degeneracy) and positive integer k means that rows ro and k were swapped.
1515 int matrix::pivot(unsigned ro, unsigned co, bool symbolic)
1519 // search first non-zero element in column co beginning at row ro
1520 while ((k<row) && (this->m[k*col+co].expand().is_zero()))
1523 // search largest element in column co beginning at row ro
1524 GINAC_ASSERT(is_exactly_a<numeric>(this->m[k*col+co]));
1525 unsigned kmax = k+1;
1526 numeric mmax = abs(ex_to<numeric>(m[kmax*col+co]));
1528 GINAC_ASSERT(is_exactly_a<numeric>(this->m[kmax*col+co]));
1529 numeric tmp = ex_to<numeric>(this->m[kmax*col+co]);
1530 if (abs(tmp) > mmax) {
1536 if (!mmax.is_zero())
1540 // all elements in column co below row ro vanish
1543 // matrix needs no pivoting
1545 // matrix needs pivoting, so swap rows k and ro
1546 ensure_if_modifiable();
1547 for (unsigned c=0; c<col; ++c)
1548 this->m[k*col+c].swap(this->m[ro*col+c]);
1553 /** Function to check that all elements of the matrix are zero.
1555 bool matrix::is_zero_matrix() const
1563 ex lst_to_matrix(const lst & l)
1565 // Find number of rows and columns
1566 size_t rows = l.nops(), cols = 0;
1567 for (auto & itr : l) {
1568 if (!is_a<lst>(itr))
1569 throw (std::invalid_argument("lst_to_matrix: argument must be a list of lists"));
1570 if (itr.nops() > cols)
1574 // Allocate and fill matrix
1575 matrix &M = *new matrix(rows, cols);
1576 M.setflag(status_flags::dynallocated);
1579 for (auto & itr : l) {
1581 for (auto & itc : ex_to<lst>(itr)) {
1591 ex diag_matrix(const lst & l)
1593 size_t dim = l.nops();
1595 // Allocate and fill matrix
1596 matrix &M = *new matrix(dim, dim);
1597 M.setflag(status_flags::dynallocated);
1600 for (auto & it : l) {
1608 ex diag_matrix(std::initializer_list<ex> l)
1610 size_t dim = l.size();
1612 // Allocate and fill matrix
1613 matrix &M = *new matrix(dim, dim);
1614 M.setflag(status_flags::dynallocated);
1617 for (auto & it : l) {
1625 ex unit_matrix(unsigned r, unsigned c)
1627 matrix &Id = *new matrix(r, c);
1628 Id.setflag(status_flags::dynallocated | status_flags::evaluated);
1629 for (unsigned i=0; i<r && i<c; i++)
1635 ex symbolic_matrix(unsigned r, unsigned c, const std::string & base_name, const std::string & tex_base_name)
1637 matrix &M = *new matrix(r, c);
1638 M.setflag(status_flags::dynallocated | status_flags::evaluated);
1640 bool long_format = (r > 10 || c > 10);
1641 bool single_row = (r == 1 || c == 1);
1643 for (unsigned i=0; i<r; i++) {
1644 for (unsigned j=0; j<c; j++) {
1645 std::ostringstream s1, s2;
1647 s2 << tex_base_name << "_{";
1658 s1 << '_' << i << '_' << j;
1659 s2 << i << ';' << j << "}";
1662 s2 << i << j << '}';
1665 M(i, j) = symbol(s1.str(), s2.str());
1672 ex reduced_matrix(const matrix& m, unsigned r, unsigned c)
1674 if (r+1>m.rows() || c+1>m.cols() || m.cols()<2 || m.rows()<2)
1675 throw std::runtime_error("minor_matrix(): index out of bounds");
1677 const unsigned rows = m.rows()-1;
1678 const unsigned cols = m.cols()-1;
1679 matrix &M = *new matrix(rows, cols);
1680 M.setflag(status_flags::dynallocated | status_flags::evaluated);
1692 M(ro2,co2) = m(ro, co);
1703 ex sub_matrix(const matrix&m, unsigned r, unsigned nr, unsigned c, unsigned nc)
1705 if (r+nr>m.rows() || c+nc>m.cols())
1706 throw std::runtime_error("sub_matrix(): index out of bounds");
1708 matrix &M = *new matrix(nr, nc);
1709 M.setflag(status_flags::dynallocated | status_flags::evaluated);
1711 for (unsigned ro=0; ro<nr; ++ro) {
1712 for (unsigned co=0; co<nc; ++co) {
1713 M(ro,co) = m(ro+r,co+c);
1720 } // namespace GiNaC