cgv
Loading...
Searching...
No Matches
det.h
1#pragma once
2#include <cgv/math/mat.h>
3#include <cgv/math/perm_mat.h>
4#include <cgv/math/diag_mat.h>
5#include <cgv/math/low_tri_mat.h>
6#include <cgv/math/up_tri_mat.h>
7#include <cgv/math/lu.h>
8
9namespace cgv {
10namespace math {
11
12//compute determinant of a diagonal matrix
13template <typename T>
14T det(const diag_mat<T>& m)
15{
16 T v = (T)1.0;
17 for(unsigned i =0; i< m.nrows(); i++)
18 v *= m(i);
19 return v;
20}
21
22//compute determinant of an lower triangular matrix
23template <typename T>
24T det(const low_tri_mat<T>& m)
25{
26 T v = (T)1.0;
27 for(unsigned i =0; i< m.nrows(); i++)
28 v *= m(i,i);
29 return v;
30}
31
32//compute determinant of an upper triangular matrix
33template <typename T>
34T det(const up_tri_mat<T>& m)
35{
36 T v = (T)1.0;
37 for(unsigned i =0; i< m.nrows(); i++)
38 v *= m(i,i);
39 return v;
40}
41
42//compute determinant of a permutation matrix
43inline int det(const perm_mat& m)
44{
45 //count number of transpositions needed to get the identity permutation
46 perm_mat temp = m;
47 unsigned num_transpositions = 0;
48 for(unsigned i = 0; i < m.size();i++)
49 {
50 while(temp(i) != i)
51 {
52 std::swap(temp(i),temp(temp(i)));
53 num_transpositions++;
54 }
55 }
56 //if number of transpositions is even return 1 else -1
57 if(num_transpositions % 2 == 0)
58 return 1;
59 else
60 return -1;
61
62}
63
64//compute determinant of a square matrix m
65template <typename T>
66T det(const mat<T>& m)
67{
68 assert(m.is_square());
69 perm_mat p;
70 low_tri_mat<T> l;
71 up_tri_mat<T> u;
72 lu(m,p,l,u);
73 return det(p)*det(l)*det(u);
74}
75
76//compute determinant of 2x2 matrix
77template<typename T>
78T det_22(const T a11,const T a12,
79 const T a21,const T a22)
80{
81 return a11*a22-a21*a12;
82}
83
84//compute determinant of 3x3 matrix
85template<typename T>
86T det_33(const T a11,const T a12,const T a13,
87 const T a21,const T a22,const T a23,
88 const T a31,const T a32,const T a33)
89
90{
91 return a11 * (a22 * a33 - a32 * a23) -
92 a21 * (a12 * a33 - a32 * a13) +
93 a31 * (a12 * a23 - a22 * a13);
94}
95
96//compute determinant of 4x4 matrix
97template<typename T>
98T det_44(const T a11,const T a12,const T a13,const T a14,
99 const T a21,const T a22,const T a23,const T a24,
100 const T a31,const T a32,const T a33,const T a34,
101 const T a41,const T a42,const T a43,const T a44)
102 {
103 T a3344 = a33 * a44 - a43 * a34;
104 T a2344 = a23 * a44 - a43 * a24;
105 T a2334 = a23 * a34 - a33 * a24;
106 T a1344 = a13 * a44 - a43 * a14;
107 T a1334 = a13 * a34 - a33 * a14;
108 T a1324 = a13 * a24 - a23 * a14;
109
110 return a11 * (a22 * a3344 - a32 * a2344 + a42 * a2334) -
111 a21 * (a12 * a3344 - a32 * a1344 + a42 * a1334) +
112 a31 * (a12 * a2344 - a22 * a1344 + a42 * a1324) -
113 a41 * (a12 * a2334 - a22 * a1334 + a32 * a1324);
114 }
115
116 }
117
118}
119
120
the cgv namespace
Definition print.h:11