source: src/LinearAlgebra/MatrixContent.cpp@ d85c28

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since d85c28 was d85c28, checked in by Frederik Heber <heber@…>, 14 years ago

Added Hadamard product by overloading MatrixContent::operator&(..) and operator&=(..).

  • the Hadamard product is a component-wise product which we need for subspace factorization.
  • Property mode set to 100644
File size: 19.7 KB
Line 
1/*
2 * MatrixContent.cpp
3 *
4 * Created on: Nov 14, 2010
5 * Author: heber
6 */
7
8
9// include config.h
10#ifdef HAVE_CONFIG_H
11#include <config.h>
12#endif
13
14#include "Helpers/MemDebug.hpp"
15
16#include "LinearAlgebra/RealSpaceMatrix.hpp"
17#include "Exceptions/NotInvertibleException.hpp"
18#include "Helpers/Assert.hpp"
19#include "Helpers/defs.hpp"
20#include "Helpers/fast_functions.hpp"
21#include "LinearAlgebra/Vector.hpp"
22#include "LinearAlgebra/VectorContent.hpp"
23#include "LinearAlgebra/MatrixContent.hpp"
24
25#include <gsl/gsl_blas.h>
26#include <gsl/gsl_eigen.h>
27#include <gsl/gsl_linalg.h>
28#include <gsl/gsl_matrix.h>
29#include <gsl/gsl_multimin.h>
30#include <gsl/gsl_vector.h>
31#include <cmath>
32#include <cassert>
33#include <iostream>
34#include <set>
35
36using namespace std;
37
38
39/** Constructor for class MatrixContent.
40 * \param rows number of rows
41 * \param columns number of columns
42 */
43MatrixContent::MatrixContent(size_t _rows, size_t _columns) :
44 rows(_rows),
45 columns(_columns)
46{
47 content = gsl_matrix_calloc(rows, columns);
48}
49
50/** Constructor of class VectorContent.
51 * We need this MatrixBaseCase for the VectorContentView class.
52 * There no content should be allocated, as it is just a view with an internal
53 * gsl_vector_view. Hence, MatrixBaseCase is just dummy class to give the
54 * constructor a unique signature.
55 * \param MatrixBaseCase
56 */
57MatrixContent::MatrixContent(size_t _rows, size_t _columns, MatrixBaseCase) :
58 rows(_rows),
59 columns(_columns)
60{}
61
62/** Constructor for class MatrixContent.
63 * \param rows number of rows
64 * \param columns number of columns
65 * \param *src array with components to initialize matrix with
66 */
67MatrixContent::MatrixContent(size_t _rows, size_t _columns, const double *src) :
68 rows(_rows),
69 columns(_columns)
70{
71 content = gsl_matrix_calloc(rows, columns);
72 set(0,0, src[0]);
73 set(1,0, src[1]);
74 set(2,0, src[2]);
75
76 set(0,1, src[3]);
77 set(1,1, src[4]);
78 set(2,1, src[5]);
79
80 set(0,2, src[6]);
81 set(1,2, src[7]);
82 set(2,2, src[8]);
83}
84
85/** Constructor for class MatrixContent.
86 * We embed the given gls_matrix pointer within this class and set it to NULL
87 * afterwards.
88 * \param *src source gsl_matrix vector to embed within this class
89 */
90MatrixContent::MatrixContent(gsl_matrix *&src) :
91 rows(src->size1),
92 columns(src->size2)
93{
94 content = gsl_matrix_alloc(src->size1, src->size2);
95 gsl_matrix_memcpy(content,src);
96// content = src;
97// src = NULL;
98}
99
100/** Copy constructor for class MatrixContent.
101 * \param &src reference to source MatrixContent
102 */
103MatrixContent::MatrixContent(const MatrixContent &src) :
104 rows(src.rows),
105 columns(src.columns)
106{
107 content = gsl_matrix_alloc(src.rows, src.columns);
108 gsl_matrix_memcpy(content,src.content);
109}
110
111/** Copy constructor for class MatrixContent.
112 * \param *src pointer to source MatrixContent
113 */
114MatrixContent::MatrixContent(const MatrixContent *src) :
115 rows(src->rows),
116 columns(src->columns)
117{
118 ASSERT(src != NULL, "MatrixContent::MatrixContent - pointer to source matrix is NULL!");
119 content = gsl_matrix_alloc(src->rows, src->columns);
120 gsl_matrix_memcpy(content,src->content);
121}
122
123/** Destructor for class MatrixContent.
124 */
125MatrixContent::~MatrixContent()
126{
127 gsl_matrix_free(content);
128}
129
130/** Set matrix to identity.
131 */
132void MatrixContent::setIdentity()
133{
134 for(int i=rows;i--;){
135 for(int j=columns;j--;){
136 set(i,j,i==j);
137 }
138 }
139}
140
141/** Set all matrix components to zero.
142 */
143void MatrixContent::setZero()
144{
145 for(int i=rows;i--;){
146 for(int j=columns;j--;){
147 set(i,j,0.);
148 }
149 }
150}
151
152/** Set all matrix components to a given value.
153 * \param _value value to set each component to
154 */
155void MatrixContent::setValue(double _value)
156{
157 for(int i=rows;i--;){
158 for(int j=columns;j--;){
159 set(i,j,_value);
160 }
161 }
162}
163
164/** Copy operator for MatrixContent with self-assignment check.
165 * \param &src matrix to compare to
166 * \return reference to this
167 */
168MatrixContent &MatrixContent::operator=(const MatrixContent &src)
169{
170 if(&src!=this){
171 gsl_matrix_memcpy(content,src.content);
172 }
173 return *this;
174}
175
176/** Addition operator.
177 * \param &rhs matrix to add
178 * \return reference to this
179 */
180const MatrixContent &MatrixContent::operator+=(const MatrixContent &rhs)
181{
182 gsl_matrix_add(content, rhs.content);
183 return *this;
184}
185
186/** Subtraction operator.
187 * \param &rhs matrix to subtract
188 * \return reference to this
189 */
190const MatrixContent &MatrixContent::operator-=(const MatrixContent &rhs)
191 {
192 gsl_matrix_sub(content, rhs.content);
193 return *this;
194}
195
196/** Multiplication operator.
197 * Note that here matrix have to have same dimensions.
198 * \param &rhs matrix to multiply with
199 * \return reference to this
200 */
201const MatrixContent &MatrixContent::operator*=(const MatrixContent &rhs)
202{
203 ASSERT(rows == rhs.rows,
204 "MatrixContent::operator*=() - row dimension differ: "+toString(rows)+" != "+toString(rhs.rows)+".");
205 ASSERT(columns == rhs.columns,
206 "MatrixContent::operator*=() - columns dimension differ: "+toString(columns)+" != "+toString(rhs.columns)+".");
207 (*this) = (*this)*rhs;
208 return *this;
209}
210
211/** Multiplication with copy operator.
212 * \param &rhs matrix to multiply with
213 * \return reference to newly allocated MatrixContent
214 */
215const MatrixContent MatrixContent::operator*(const MatrixContent &rhs) const
216{
217 ASSERT (columns == rhs.rows,
218 "MatrixContent::operator*() - dimensions not match for matrix product (a,b)*(b,c) = (a,c):"
219 "("+toString(rows)+","+toString(columns)+")*("+toString(rhs.rows)+","+toString(rhs.columns)+")");
220 gsl_matrix *res = gsl_matrix_alloc(rows, rhs.columns);
221 gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, content, rhs.content, 0.0, res);
222 // gsl_matrix is taken over by constructor, hence no free
223 MatrixContent tmp(res);
224 gsl_matrix_free(res);
225 return tmp;
226}
227
228/** Hadamard multiplication with copy operator.
229 * The Hadamard product is component-wise matrix product.
230 * \param &rhs matrix to hadamard-multiply with
231 * \return reference to newly allocated MatrixContent
232 */
233const MatrixContent MatrixContent::operator&(const MatrixContent &rhs) const
234{
235 ASSERT ((rows == rhs.rows) && (columns == rhs.columns),
236 "MatrixContent::operator&() - dimensions not match for matrix product (a,b) != (b,c):"
237 "("+toString(rows)+","+toString(columns)+") != ("+toString(rhs.rows)+","+toString(rhs.columns)+")");
238 gsl_matrix *res = gsl_matrix_alloc(rows, rhs.columns);
239 for (size_t i=0;i<rows;++i)
240 for (size_t j=0;j<columns;++j)
241 gsl_matrix_set(res, i,j, gsl_matrix_get(content, i,j)*gsl_matrix_get(rhs.content, i,j));
242 // gsl_matrix is taken over by constructor, hence no free
243 MatrixContent tmp(res);
244 gsl_matrix_free(res);
245 return tmp;
246}
247
248/** Hadamard multiplication with copy operator.
249 * The Hadamard product is component-wise matrix product.
250 * Note that Hadamard product can easily be done on top of \a *this matrix.
251 * Hence, we don't need to use the multiply and copy operator as in the case of
252 * MatrixContent::operator*=().
253 * \param &rhs matrix to hadamard-multiply with
254 * \return reference to newly allocated MatrixContent
255 */
256const MatrixContent &MatrixContent::operator&=(const MatrixContent &rhs)
257{
258 ASSERT ((rows == rhs.rows) && (columns == rhs.columns),
259 "MatrixContent::operator&() - dimensions not match for matrix product (a,b) != (b,c):"
260 "("+toString(rows)+","+toString(columns)+") != ("+toString(rhs.rows)+","+toString(rhs.columns)+")");
261 for (size_t i=0;i<rows;++i)
262 for (size_t j=0;j<columns;++j)
263 gsl_matrix_set(content, i,j, gsl_matrix_get(content, i,j)*gsl_matrix_get(rhs.content, i,j));
264 return *this;
265}
266
267/* ========================== Accessing =============================== */
268
269/** Accessor for manipulating component (i,j).
270 * \param i row number
271 * \param j column number
272 * \return reference to component (i,j)
273 */
274double &MatrixContent::at(size_t i, size_t j)
275{
276 ASSERT((i>=0) && (i<rows),
277 "MatrixContent::at() - Index i="+toString(i)+" for Matrix access out of range [0,"+toString(rows)+"]");
278 ASSERT((j>=0) && (j<columns),
279 "MatrixContent::at() - Index j="+toString(j)+" for Matrix access out of range [0,"+toString(columns)+"]");
280 return *gsl_matrix_ptr (content, i, j);
281}
282
283/** Constant accessor for (value of) component (i,j).
284 * \param i row number
285 * \param j column number
286 * \return const component (i,j)
287 */
288const double MatrixContent::at(size_t i, size_t j) const
289{
290 ASSERT((i>=0) && (i<rows),
291 "MatrixContent::at() - Index i="+toString(i)+" for Matrix access out of range [0,"+toString(rows)+"]");
292 ASSERT((j>=0) && (j<columns),
293 "MatrixContent::at() - Index j="+toString(j)+" for Matrix access out of range [0,"+toString(columns)+"]");
294 return gsl_matrix_get(content, i, j);
295}
296
297/** These functions return a pointer to the \a m-th element of a matrix.
298 * If \a m or \a n lies outside the allowed range of 0 to MatrixContent::dimension-1 then the error handler is invoked and a null pointer is returned.
299 * \param m index
300 * \return pointer to \a m-th element
301 */
302double *MatrixContent::Pointer(size_t m, size_t n)
303{
304 return gsl_matrix_ptr (content, m, n);
305};
306
307/** These functions return a constant pointer to the \a m-th element of a matrix.
308 * If \a m or \a n lies outside the allowed range of 0 to MatrixContent::dimension-1 then the error handler is invoked and a null pointer is returned.
309 * \param m index
310 * \return const pointer to \a m-th element
311 */
312const double *MatrixContent::const_Pointer(size_t m, size_t n) const
313{
314 return gsl_matrix_const_ptr (content, m, n);
315};
316
317/* ========================== Initializing =============================== */
318
319/** Setter for component (i,j).
320 * \param i row numbr
321 * \param j column numnber
322 * \param value value to set componnt (i,j) to
323 */
324void MatrixContent::set(size_t i, size_t j, const double value)
325{
326 ASSERT((i>=0) && (i<rows),
327 "MatrixContent::set() - Index i="+toString(i)+" for Matrix access out of range [0,"+toString(rows)+"]");
328 ASSERT((j>=0) && (j<columns),
329 "MatrixContent::set() - Index j="+toString(j)+" for Matrix access out of range [0,"+toString(columns)+"]");
330 gsl_matrix_set(content,i,j,value);
331}
332
333/** This function sets the matrix from a double array.
334 * Creates a matrix view of the array and performs a memcopy.
335 * \param *x array of values (no dimension check is performed)
336 */
337void MatrixContent::setFromDoubleArray(double * x)
338{
339 gsl_matrix_view m = gsl_matrix_view_array (x, rows, columns);
340 gsl_matrix_memcpy (content, &m.matrix);
341};
342
343/* ====================== Exchanging elements ============================ */
344/** This function exchanges the \a i-th and \a j-th row of the matrix in-place.
345 * \param i i-th row to swap with ...
346 * \param j ... j-th row to swap against
347 */
348bool MatrixContent::SwapRows(size_t i, size_t j)
349{
350 return (gsl_matrix_swap_rows (content, i, j) == GSL_SUCCESS);
351};
352
353/** This function exchanges the \a i-th and \a j-th column of the matrix in-place.
354 * \param i i-th column to swap with ...
355 * \param j ... j-th column to swap against
356 */
357bool MatrixContent::SwapColumns(size_t i, size_t j)
358{
359 return (gsl_matrix_swap_columns (content, i, j) == GSL_SUCCESS);
360};
361
362/** This function exchanges the \a i-th row and \a j-th column of the matrix in-place.
363 * The matrix must be square for this operation to be possible.
364 * \param i i-th row to swap with ...
365 * \param j ... j-th column to swap against
366 */
367bool MatrixContent::SwapRowColumn(size_t i, size_t j)
368{
369 assert (rows == columns && "The matrix must be square for swapping row against column to be possible.");
370 return (gsl_matrix_swap_rowcol (content, i, j) == GSL_SUCCESS);
371};
372
373/** Return transposed matrix.
374 * \return new matrix that is transposed of this.
375 */
376MatrixContent MatrixContent::transpose() const
377{
378 gsl_matrix *res = gsl_matrix_alloc(columns, rows); // column and row dimensions exchanged!
379 gsl_matrix_transpose_memcpy(res, content);
380 MatrixContent newContent(res);
381 gsl_matrix_free(res);
382 return newContent;
383}
384
385/** Turn this matrix into its transposed.
386 * Note that this is only possible if rows == columns.
387 */
388MatrixContent &MatrixContent::transpose()
389{
390 ASSERT( rows == columns,
391 "MatrixContent::transpose() - cannot transpose onto itself as matrix not square: "+toString(rows)+"!="+toString(columns)+"!");
392 double tmp;
393 for (size_t i=0;i<rows;i++)
394 for (size_t j=i+1;j<rows;j++) {
395 tmp = at(j,i);
396 at(j,i) = at(i,j);
397 at(i,j) = tmp;
398 }
399 return *this;
400}
401
402/** Transform the matrix to its eigenbasis and return resulting eigenvalues.
403 * Note that we only return real-space part in case of non-symmetric matrix.
404 * \warn return vector has to be freed'd
405 * TODO: encapsulate return value in boost::shared_ptr or in VectorContent.
406 * \return gsl_vector pointer to vector of eigenvalues
407 */
408gsl_vector* MatrixContent::transformToEigenbasis()
409{
410 if (rows == columns) { // symmetric
411 gsl_eigen_symmv_workspace *T = gsl_eigen_symmv_alloc(rows);
412 gsl_vector *eval = gsl_vector_alloc(rows);
413 gsl_matrix *evec = gsl_matrix_alloc(rows, rows);
414 gsl_eigen_symmv(content, eval, evec, T);
415 gsl_eigen_symmv_free(T);
416 gsl_matrix_memcpy(content, evec);
417 gsl_matrix_free(evec);
418 return eval;
419 } else { // non-symmetric
420 // blow up gsl_matrix in content to square matrix, fill other components with zero
421 const size_t greaterDimension = rows > columns ? rows : columns;
422 gsl_matrix *content_square = gsl_matrix_alloc(greaterDimension, greaterDimension);
423 for (size_t i=0; i<greaterDimension; i++) {
424 for (size_t j=0; j<greaterDimension; j++) {
425 const double value = ((i < rows) && (j < columns)) ? gsl_matrix_get(content,i,j) : 0.;
426 gsl_matrix_set(content_square, i,j, value);
427 }
428 }
429
430 // show squared matrix by putting it into a MatrixViewContent
431 MatrixContent *ContentSquare = new MatrixViewContent(gsl_matrix_submatrix(content_square,0,0,content_square->size1, content_square->size2));
432 std::cout << "The squared matrix is " << *ContentSquare << std::endl;
433
434 // solve eigenvalue problem
435 gsl_eigen_nonsymmv_workspace *T = gsl_eigen_nonsymmv_alloc(rows);
436 gsl_vector_complex *eval = gsl_vector_complex_alloc(greaterDimension);
437 gsl_matrix_complex *evec = gsl_matrix_complex_alloc(greaterDimension, greaterDimension);
438 gsl_eigen_nonsymmv(content_square, eval, evec, T);
439 gsl_eigen_nonsymmv_free(T);
440
441 // copy eigenvectors real-parts into content_square and ...
442 for (size_t i=0; i<greaterDimension; i++)
443 for (size_t j=0; j<greaterDimension; j++)
444 gsl_matrix_set(content_square, i,j, GSL_REAL(gsl_matrix_complex_get(evec,i,j)));
445
446 // ... show complex-valued eigenvector matrix
447 std::cout << "The real-value eigenvector matrix is " << *ContentSquare << std::endl;
448// std::cout << "Resulting eigenvector matrix is [";
449// for (size_t i=0; i<greaterDimension; i++) {
450// for (size_t j=0; j<greaterDimension; j++) {
451// std::cout << "(" << GSL_REAL(gsl_matrix_complex_get(evec,i,j))
452// << "," << GSL_IMAG(gsl_matrix_complex_get(evec,i,j)) << ")";
453// if (j < greaterDimension-1)
454// std::cout << " ";
455// }
456// if (i < greaterDimension-1)
457// std::cout << "; ";
458// }
459// std::cout << "]" << std::endl;
460
461 // copy real-parts of complex eigenvalues and eigenvectors (column-wise orientation)
462 gsl_vector *eval_real = gsl_vector_alloc(columns);
463 size_t I=0;
464 for (size_t i=0; i<greaterDimension; i++) { // only copy real space part
465 if (fabs(GSL_REAL(gsl_vector_complex_get(eval,i))) > MYEPSILON) { // only take eigenvectors with value > 0
466 std::cout << i << "th eigenvalue is (" << GSL_REAL(gsl_vector_complex_get(eval,i)) << "," << GSL_IMAG(gsl_vector_complex_get(eval,i)) << ")" << std::endl;
467 for (size_t j=0; j<greaterDimension; j++) {
468 if (fabs(GSL_IMAG(gsl_matrix_complex_get(evec,j,i))) > MYEPSILON)
469 std::cerr << "MatrixContent::transformToEigenbasis() - WARNING: eigenvectors are complex-valued!" << std::endl;
470 gsl_matrix_set(content, j,I, GSL_REAL(gsl_matrix_complex_get(evec,j,i)));
471 }
472 if (fabs(GSL_IMAG(gsl_vector_complex_get(eval,I))) > MYEPSILON)
473 std::cerr << "MatrixContent::transformToEigenbasis() - WARNING: eigenvectors are complex-valued!" << std::endl;
474 gsl_vector_set(eval_real, I, GSL_REAL(gsl_vector_complex_get(eval, i)));
475 I++;
476 }
477 }
478 gsl_matrix_complex_free(evec);
479 gsl_vector_complex_free(eval);
480 delete ContentSquare;
481
482 return eval_real;
483 }
484}
485
486/* ============================ Properties ============================== */
487/** Checks whether matrix' elements are strictly null.
488 * \return true - is null, false - else
489 */
490bool MatrixContent::IsNull() const
491{
492 return gsl_matrix_isnull (content);
493};
494
495/** Checks whether matrix' elements are strictly positive.
496 * \return true - is positive, false - else
497 */
498bool MatrixContent::IsPositive() const
499{
500 return gsl_matrix_ispos (content);
501};
502
503/** Checks whether matrix' elements are strictly negative.
504 * \return true - is negative, false - else
505 */
506bool MatrixContent::IsNegative() const
507{
508 return gsl_matrix_isneg (content);
509};
510
511/** Checks whether matrix' elements are strictly non-negative.
512 * \return true - is non-negative, false - else
513 */
514bool MatrixContent::IsNonNegative() const
515{
516 return gsl_matrix_isnonneg (content);
517};
518
519/** This function performs a Cholesky decomposition to determine whether matrix is positive definite.
520 * We check whether GSL returns GSL_EDOM as error, indicating that decomposition failed due to matrix not being positive-definite.
521 * \return true - matrix is positive-definite, false - else
522 */
523bool MatrixContent::IsPositiveDefinite() const
524{
525 if (rows != columns) // only possible for square matrices.
526 return false;
527 else
528 return (gsl_linalg_cholesky_decomp (content) != GSL_EDOM);
529};
530
531
532/** Calculates the determinant of the matrix.
533 * if matrix is square, uses LU decomposition.
534 */
535double MatrixContent::Determinant() const
536{
537 int signum = 0;
538 assert (rows == columns && "Determinant can only be calculated for square matrices.");
539 gsl_permutation *p = gsl_permutation_alloc(rows);
540 gsl_linalg_LU_decomp(content, p, &signum);
541 gsl_permutation_free(p);
542 return gsl_linalg_LU_det(content, signum);
543};
544
545/* ============================= Operators =============================== */
546
547/** Scalar multiplication operator.
548 * \param factor factor to scale with
549 */
550const MatrixContent &MatrixContent::operator*=(const double factor)
551{
552 gsl_matrix_scale(content, factor);
553 return *this;
554}
555
556/** Scalar multiplication and copy operator.
557 * \param factor factor to scale with
558 * \param &mat MatrixContent to scale
559 * \return copied and scaled MatrixContent
560 */
561const MatrixContent operator*(const double factor,const MatrixContent& mat)
562{
563 MatrixContent tmp = mat;
564 tmp*=factor;
565 return tmp;
566}
567
568/** Scalar multiplication and copy operator (with operands exchanged).
569 * \param &mat MatrixContent to scale
570 * \param factor factor to scale with
571 * \return copied and scaled MatrixContent
572 */
573const MatrixContent operator*(const MatrixContent &mat,const double factor)
574{
575 return factor*mat;
576}
577
578/** Equality operator.
579 * Note that we use numerical sensible checking, i.e. with threshold MYEPSILON.
580 * \param &rhs MatrixContent to checks against
581 */
582bool MatrixContent::operator==(const MatrixContent &rhs) const
583 {
584 if ((rows == rhs.rows) && (columns == rhs.columns)) {
585 for(int i=rows;i--;){
586 for(int j=columns;j--;){
587 if(fabs(at(i,j)-rhs.at(i,j))>MYEPSILON){
588 return false;
589 }
590 }
591 }
592 return true;
593 }
594 return false;
595}
596
597Vector operator*(const MatrixContent &mat,const Vector &vec)
598{
599 Vector result;
600 gsl_blas_dgemv( CblasNoTrans, 1.0, mat.content, vec.content->content, 0.0, result.content->content);
601 return result;
602}
603
604std::ostream & operator<<(std::ostream &ost, const MatrixContent &mat)
605{
606 ost << "[";
607 for (size_t i=0;i<mat.rows;i++) {
608 for (size_t j=0;j<mat.columns;j++) {
609 ost << mat.at(i,j);
610 if (j != mat.columns-1)
611 ost << " ";
612 }
613 if (i != mat.rows-1)
614 ost << "; ";
615 }
616 ost << "]";
617 return ost;
618}
Note: See TracBrowser for help on using the repository browser.