当前位置:   article > 正文

逆矩阵介绍及C++/OpenCV/Eigen的三种实现_c++ eigen 逆矩阵

c++ eigen 逆矩阵

逆矩阵(inverse matrix):在线性代数中,给定一个n阶方阵A,若存在一n阶方阵B,使得AB = BA =In,其中In为n阶单位矩阵,则称A是可逆的,且B是A的逆矩阵,记作A-1.只有正方形(n*n)的矩阵,亦即方阵,才可能、但非必然有逆矩阵。若方阵A的逆矩阵存在,则称A为非奇异方阵或可逆方阵。与行列式类似,逆矩阵一般常用于求解包含数个变数的数学方程式。

线性方程组:Ax = b ,如下,其中A是一个已知矩阵,b是一个已知向量,x是我们要求解的未知向量。向量x的每一个元素xi都是未知的。矩阵A的每一行和b中对应的元素构成一个约束。


线性代数提供了被称为矩阵逆(matrix inversion)的强大工具,对于大多数矩阵A,我们都能通过矩阵逆解析地求解式Ax=b。

单位矩阵(identity matrix):任意向量和单位矩阵相乘,都不会改变。我们将保持n维向量不变的单位矩阵记作In,形式上如下,

单位矩阵的结构很简单:所有沿主对角线的元素都是1,而所有其他位置的元素都是0。

矩阵A的矩阵逆(matrix inversion)记作A-1,其定义的矩阵满足如下条件:A-1A = In,可以通过A-1求解Ax = b,即x = A-1b。当然,这取决于我们能否找到一个逆矩阵A-1.

当逆矩阵A-1存在时,有几种不同的算法都能找到它的闭解形式。理论上,相同的逆矩阵可用于多次求解不同向量b的方程。

逆矩阵性质:

(1)、若矩阵A是可逆的,则A的逆矩阵是唯一的。

(2)、可逆矩阵一定是方阵。

(3)、A的逆矩阵的逆矩阵还是A,记作(A-1)-1=A.

(4)、可逆矩阵A的转置矩阵AT也可逆,并且(AT)-1=(A-1)T(转置的逆等于逆的转置)。

(5)、若矩阵A可逆,则矩阵A满足消去律,若AB=I(或BA=I),则B=I,若AB=AC(或BA=CA),则B=C。

(6)、两个可逆矩阵的乘积依然可逆。

(7)、矩阵可逆当且仅当它是满秩矩阵。

(8)、(λA)-1=(1/λ)*A-1

(9)、(AB)-1=B-1A-1

(10)、det(A-1)=1/det(A) (det为行列式)

(11)、方阵A可逆的充分必要条件是|A|≠0,并且A-1=(1/|A|)A*,其中A*是A的伴随矩阵。即可逆矩阵就是非奇异矩阵(当|A|=0时,A称为奇异矩阵)。

如果逆矩阵A-1存在,对于式Ax = b,肯定对于每一个向量b恰好存在一个解。

线性组合(linear combination):形式上,一组向量的线性组合,是指每个向量乘以对应标量系数之后的和,即:


生成子空间(span):一组向量的生成子空间是原始向量线性组合后所能抵达的点的集合。

确定Ax = b是否有解相当于确定向量b是否在A列向量的生成子空间中。这个特殊的生成子空间被称为A的列空间(column space)或者A的值域(range)。

线性无关(linearly independent):如果一组向量中的任意一个向量都不能表示成其他向量的线性组合,那么这组向量被称为线性无关,反之称为线性相关(linearly  dependent)。如果某个向量是一组向量中某些向量的线性组合,那么我们将这个向量加入到这组向量后不会增加这组向量的生成子空间。这意味着,如果一个矩阵的列空间涵盖整个Rm,那么该矩阵必须包含至少一组m个线性无关的向量。这是式Ax = b对于每一个向量b的取值都有解的充分必要条件。值得注意的是,这个条件是说该向量集恰好有m个线性无关的列向量,而不是至少m个。不存在一个m维向量的集合具有多于m个彼此线性不相关的列向量,但是一个有多于m个列向量的矩阵却有可能拥有不止一个大小为m的线性无关向量集。

要想使矩阵可逆,我们还需要保证式Ax = b对于每一个b值至多有一个解。为此,我们需要确保该矩阵至多有m个列向量。否则,该方程会有不止一个解。

综上所述,这意味着该矩阵必须是一个方阵(square),即m = n,并且所有列向量都是线性无关的。一个列向量线性相关的方阵被称为奇异的(singular)。

如果矩阵A不是一个方阵或者是一个奇异的方阵,该方程仍然可能有解。但是我们不能使用矩阵逆去求解。

对于方阵而言,矩阵的左逆和右逆是相等的:AA-1=A-1A=I

以上内容来自于 维基百科 和 《深度学习中文版》(https://github.com/exacity/deeplearningbook-chinese)

以下是分别用C++和OpenCV实现的矩阵求逆:

  1. #include "funset.hpp"
  2. #include <math.h>
  3. #include <iostream>
  4. #include <string>
  5. #include <vector>
  6. #include <opencv2/opencv.hpp>
  7. #include "common.hpp"
  8. #define EXP 1.0e-5
  9. // 计算行列式
  10. template<typename _Tp>
  11. _Tp determinant(const std::vector<std::vector<_Tp>>& mat, int N)
  12. {
  13. if (mat.size() != N) {
  14. fprintf(stderr, "mat must be square matrix\n");
  15. return -1;
  16. }
  17. for (int i = 0; i < mat.size(); ++i) {
  18. if (mat[i].size() != N) {
  19. fprintf(stderr, "mat must be square matrix\n");
  20. return -1;
  21. }
  22. }
  23. _Tp ret{ 0 };
  24. if (N == 1) return mat[0][0];
  25. if (N == 2) {
  26. return (mat[0][0] * mat[1][1] - mat[0][1] * mat[1][0]);
  27. }
  28. else {
  29. // first col
  30. for (int i = 0; i < N; ++i) {
  31. std::vector<std::vector<_Tp>> m(N - 1);
  32. std::vector<int> m_rows;
  33. for (int t = 0; t < N; ++t) {
  34. if (i != t) m_rows.push_back(t);
  35. }
  36. for (int x = 0; x < N - 1; ++x) {
  37. m[x].resize(N - 1);
  38. for (int y = 0; y < N - 1; ++y) {
  39. m[x][y] = mat[m_rows[x]][y + 1];
  40. }
  41. }
  42. int sign = (int)pow(-1, 1 + i + 1);
  43. ret += mat[i][0] * sign * determinant<_Tp>(m, N - 1);
  44. }
  45. }
  46. return ret;
  47. }
  48. // 计算伴随矩阵
  49. template<typename _Tp>
  50. int adjoint(const std::vector<std::vector<_Tp>>& mat, std::vector<std::vector<_Tp>>& adj, int N)
  51. {
  52. if (mat.size() != N) {
  53. fprintf(stderr, "mat must be square matrix\n");
  54. return -1;
  55. }
  56. for (int i = 0; i < mat.size(); ++i) {
  57. if (mat[i].size() != N) {
  58. fprintf(stderr, "mat must be square matrix\n");
  59. return -1;
  60. }
  61. }
  62. adj.resize(N);
  63. for (int i = 0; i < N; ++i) {
  64. adj[i].resize(N);
  65. }
  66. for (int y = 0; y < N; ++y) {
  67. std::vector<int> m_cols;
  68. for (int i = 0; i < N; ++i) {
  69. if (i != y) m_cols.push_back(i);
  70. }
  71. for (int x = 0; x < N; ++x) {
  72. std::vector<int> m_rows;
  73. for (int i = 0; i < N; ++i) {
  74. if (i != x) m_rows.push_back(i);
  75. }
  76. std::vector<std::vector<_Tp>> m(N - 1);
  77. for (int i = 0; i < N - 1; ++i) {
  78. m[i].resize(N - 1);
  79. }
  80. for (int j = 0; j < N - 1; ++j) {
  81. for (int i = 0; i < N - 1; ++i) {
  82. m[j][i] = mat[m_rows[j]][m_cols[i]];
  83. }
  84. }
  85. int sign = (int)pow(-1, x + y);
  86. adj[y][x] = sign * determinant<_Tp>(m, N-1);
  87. }
  88. }
  89. return 0;
  90. }
  91. template<typename _Tp>
  92. void print_matrix(const std::vector<std::vector<_Tp>>& mat)
  93. {
  94. int rows = mat.size();
  95. for (int y = 0; y < rows; ++y) {
  96. for (int x = 0; x < mat[y].size(); ++x) {
  97. fprintf(stderr, " %f ", mat[y][x]);
  98. }
  99. fprintf(stderr, "\n");
  100. }
  101. fprintf(stderr, "\n");
  102. }
  103. void print_matrix(const cv::Mat& mat)
  104. {
  105. assert(mat.channels() == 1);
  106. for (int y = 0; y < mat.rows; ++y) {
  107. for (int x = 0; x < mat.cols; ++x) {
  108. if (mat.depth() == CV_8U) {
  109. unsigned char value = mat.at<uchar>(y, x);
  110. fprintf(stderr, " %d ", value);
  111. }
  112. else if (mat.depth() == CV_32F) {
  113. float value = mat.at<float>(y, x);
  114. fprintf(stderr, " %f ", value);
  115. }
  116. else if (mat.depth() == CV_64F) {
  117. double value = mat.at<double>(y, x);
  118. fprintf(stderr, " %f ", value);
  119. }
  120. else {
  121. fprintf(stderr, "don't support type: %d\n", mat.depth());
  122. return;
  123. }
  124. }
  125. fprintf(stderr, "\n");
  126. }
  127. fprintf(stderr, "\n");
  128. }
  129. // 求逆矩阵
  130. template<typename _Tp>
  131. int inverse(const std::vector<std::vector<_Tp>>& mat, std::vector<std::vector<_Tp>>& inv, int N)
  132. {
  133. if (mat.size() != N) {
  134. fprintf(stderr, "mat must be square matrix\n");
  135. return -1;
  136. }
  137. for (int i = 0; i < mat.size(); ++i) {
  138. if (mat[i].size() != N) {
  139. fprintf(stderr, "mat must be square matrix\n");
  140. return -1;
  141. }
  142. }
  143. _Tp det = determinant(mat, N);
  144. if (fabs(det) < EXP) {
  145. fprintf(stderr, "mat's determinant don't equal 0\n");
  146. return -1;
  147. }
  148. inv.resize(N);
  149. for (int i = 0; i < N; ++i) {
  150. inv[i].resize(N);
  151. }
  152. double coef = 1.f / det;
  153. std::vector<std::vector<_Tp>> adj;
  154. if (adjoint(mat, adj, N) != 0) return -1;
  155. for (int y = 0; y < N; ++y) {
  156. for (int x = 0; x < N; ++x) {
  157. inv[y][x] = (_Tp)(coef * adj[y][x]);
  158. }
  159. }
  160. return 0;
  161. }
  162. int test_inverse_matrix()
  163. {
  164. std::vector<float> vec{ 5, -2, 2, 7, 1, 0, 0, 3, -3, 1, 5, 0, 3, -1, -9, 4 };
  165. const int N{ 4 };
  166. if (vec.size() != (int)pow(N, 2)) {
  167. fprintf(stderr, "vec must be N^2\n");
  168. return -1;
  169. }
  170. std::vector<std::vector<float>> arr(N);
  171. for (int i = 0; i < N; ++i) {
  172. arr[i].resize(N);
  173. for (int j = 0; j < N; ++j) {
  174. arr[i][j] = vec[i * N + j];
  175. }
  176. }
  177. std::vector<std::vector<float>> inv1;
  178. int ret = inverse<float>(arr, inv1, N);
  179. fprintf(stderr, "source matrix: \n");
  180. print_matrix<float>(arr);
  181. fprintf(stderr, "c++ inverse matrix: \n");
  182. print_matrix<float>(inv1);
  183. cv::Mat mat(N, N, CV_32FC1, vec.data());
  184. cv::Mat inv2 = mat.inv();
  185. fprintf(stderr, "opencv inverse matrix: \n");
  186. print_matrix(inv2);
  187. return 0;
  188. }
执行结果如下:

以下是用Eigen实现的矩阵求逆:

  1. #include "funset.hpp"
  2. #include <math.h>
  3. #include <iostream>
  4. #include <vector>
  5. #include <string>
  6. #include <opencv2/opencv.hpp>
  7. #include <Eigen/Dense>
  8. #include "common.hpp"
  9. template<typename _Tp>
  10. void print_matrix(const _Tp* data, const int rows, const int cols)
  11. {
  12. for (int y = 0; y < rows; ++y) {
  13. for (int x = 0; x < cols; ++x) {
  14. fprintf(stderr, " %f ", static_cast<float>(data[y * cols + x]));
  15. }
  16. fprintf(stderr, "\n");
  17. }
  18. fprintf(stderr, "\n");
  19. }
  20. int test_inverse_matrix()
  21. {
  22. std::vector<float> vec{ 5, -2, 2, 7, 1, 0, 0, 3, -3, 1, 5, 0, 3, -1, -9, 4 };
  23. const int N{ 4 };
  24. if (vec.size() != (int)pow(N, 2)) {
  25. fprintf(stderr, "vec must be N^2\n");
  26. return -1;
  27. }
  28. Eigen::Map<Eigen::MatrixXf> map(vec.data(), 4, 4);
  29. Eigen::MatrixXf inv = map.inverse();
  30. fprintf(stderr, "source matrix:\n");
  31. print_matrix<float>(vec.data(), N, N);
  32. fprintf(stderr, "eigen inverse matrix:\n");
  33. print_matrix<float>(inv.data(), N, N);
  34. return 0;
  35. }
执行结果如下:


可见,三种实现方法结果是一致的。

GitHub

https://github.com/fengbingchun/NN_Test

https://github.com/fengbingchun/Eigen_Test

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/79239
推荐阅读
相关标签
  

闽ICP备14008679号