2014-02-27 296 views
2

我正在使用Eigen(自由線性代數包與C++一起使用)並嘗試反轉一個小矩陣。繼官方Eigen文檔後,我得到以下內容:Eigen未能給出正確的矩陣求逆(C++)

#include <iostream> 
using namespace std; 
#include <Eigen/LU> 
#include <Eigen/Dense> 
using namespace Eigen; 

Matrix3d k = Matrix3d::Random(); 
cout << "Here is the matrix k:" << endl << k << endl; 
cout << "Its inverse is:" << endl << k.inverse() << endl; 
cout << "The product of the two (supposedly the identity) is:" << endl << k.inverse()*k << endl; 

這就給了我正確的答案。但是,如果不是將k作爲一個隨機分配的矩陣,而是創建一個矩陣,然後自己分配所有的值,它會給我一個錯誤的逆。例如,下面的代碼會給我錯誤的反面。

Matrix3d m; 
Matrix3d mi; 
for (int i = 0; i < 3; ++ i) 
    for (int j = 0; j < 3; ++ j) 
     m (i, j) = i + 3.0*j; 

std::cout << "m is " << m << std::endl; 
mi = m.inverse(); 
std::cout << "mi is " << mi << std::endl; 
std::cout << "product of m and m_inverse is " << (mi*m) << std::endl; 

我想能夠反轉我爲其分配了值的矩陣。誰能告訴我這裏發生了什麼?爲什麼Eigen正在這樣做?

+0

矩陣是不可逆的是通常的原因.... –

+1

你的矩陣是不可逆的。你期望什麼樣的結果? –

+0

啊,就是這樣。如果是這樣,我也嘗試了其他幾個矩陣,但事實證明它們也是單一的。感謝您收到 – user3358834

回答

11

你的矩陣是這樣的:

0 3 6 
1 4 7 
2 5 8 

,如果你從2行和ROW3減去ROW1,您可以:

0 3 6 
1 1 1 
2 2 2 

,然後減去ROW3 2 * 2行,你會得到:

0 3 6 
1 1 1 
0 0 0 

這意味着矩陣是奇異的!這意味着矩陣不能倒置!

您選擇矩陣的方式非常不幸。

+2

+1。我知道這僅僅是通過查看定義而得到的,但是寫起來不會感到困擾! –