連立一次方程式を解きたい


Tips

解説

線型方程式 A x = b (A : N×N行列; x, b :N次元ベクトル)を解く。 ComplexMatrix Aを定義し、 そのComplexColumnVector A.solve(ComplexColumnVector &b)メソッドを使う。 bをN×M行列(ComplexMatrix b(N,M))とすると、 M個の連立方程式が同時に求められる模様。

サンプルプログラム

filele.cpp

#include <iostream>
#include <octave/config.h>
#include <octave/CMatrix.h>

using namespace std; 

int main()
{
  //using namespace boost;
  //cout.setf(ios::fixed);

  int const N = 4;
  Complex const IU(0.0, 1.0);

  ComplexMatrix A(N, N);
  A(0,0) = 3.0 + IU; A(0,1) = 2.0       ; A(0,2) = IU     ; A(0,3) = -IU;
  A(1,0) = 4.0     ; A(1,1) = 1.0 + IU  ; A(1,2) = 6.0    ; A(1,3) = 2.0;
  A(2,0) = 5.0*IU  ; A(2,1) = 3.0 - IU  ; A(2,2) = -4.0*IU; A(2,3) = -3.0;
  A(3,0) = -2.0    ; A(3,1) = 1.0-5.0*IU; A(3,2) = 3.0    ; A(3,3) = -1.0+IU;
 
  cout << "A = " << endl << A << endl;

  ComplexColumnVector b(N);  
  b(0) = 3.0;
  b(1) = 1.0;
  b(2) = -2.0;
  b(3) = 2.0+IU;
  cout << "b = " << endl << b << endl;
  
  ComplexColumnVector x(N);
  x = A.solve(b);

  cout << "x = " << endl << x << endl;

  cout << "A x = " << endl << A*x << endl;
}

出力

A = 
 (3,1) (2,0) (0,1) (-0,-1)
 (4,0) (1,1) (6,0) (2,0)
 (0,5) (3,-1) (-0,-4) (-3,0)
 (-2,0) (1,-5) (3,0) (-1,1)

b = 
(3,0)
(1,0)
(-2,0)
(2,1)

x = 
(0.23398,-0.4656)
(-0.189714,1.16439)
(-0.114216,-0.442006)
(1.05174,1.76988)

A x = 
(3,0)
(1,-4.44089e-16)
(-2,2.22045e-16)
(2,1)

コメント