2017-10-29 4 views
2

に2次元配列を解釈 問題は、私の場合はFunc<double[], double> functionあるNonlinearObjectiveFunction機能テイク引数functionはそれがはのFunc私は非線形制約付き非線形関数を解決するためにアコードの数学を使用しています<double[]>

x => 
x[0] * (Matrix[0, 0] * x[0] + Matrix[1, 0] * x[1] + Matrix[2, 0] * x[2]) + 
x[1] * (Matrix[0, 1] * x[0] + Matrix[1, 1] * x[1] + Matrix[2, 1] * x[2]) + 
x[2] * (Matrix[0, 2] * x[0] + Matrix[1, 2] * x[1] + Matrix[2, 2] * x[2]) 

のようなものそれはだということです何とかこれを構築するにはfunctionサイクルを使用していますか?入力行列の次元が変わる可能性があるためです。

class Program 
    { 
     static void Main(string[] args) 
     { 
      double[,] Matrix = new double[3, 3]; 

      Matrix[0, 0] = 0.00234329; 
      Matrix[0, 1] = 0.00118878; 
      Matrix[0, 2] = 0.00152143; 
      Matrix[1, 0] = 0.00118878; 
      Matrix[1, 1] = 0.00206312; 
      Matrix[1, 2] = 0.00124812; 
      Matrix[2, 0] = 0.00152143; 
      Matrix[2, 1] = 0.00124812; 
      Matrix[2, 2] = 0.00194796; 

      double x1 = 0.0107; 
      double x2 = -0.00054; 
      double x3 = -0.0034; 

      var f = new NonlinearObjectiveFunction(3, x => 
      x[0] * (Matrix[0, 0] * x[0] + Matrix[1, 0] * x[1] + Matrix[2, 0] * x[2]) + 
      x[1] * (Matrix[0, 1] * x[0] + Matrix[1, 1] * x[1] + Matrix[2, 1] * x[2]) + 
      x[2] * (Matrix[0, 2] * x[0] + Matrix[1, 2] * x[1] + Matrix[2, 2] * x[2]) 
      ); 

      var constraints = new[] 
      { 
       new NonlinearConstraint(3, x => x1 * x[0] + x2 * x[1] + x3 * x[2] >= 0.01), 
       new NonlinearConstraint(3, x=> x[0] + x[1] + x[2]>=1), 
       new NonlinearConstraint(3, x=> x[0] + x[1] + x[2]<=1), 
       new NonlinearConstraint(3, x=> x[0]>=0), 
       new NonlinearConstraint(3, x=> x[1]>=0), 
       new NonlinearConstraint(3, x=> x[2]>=0) 
      }; 

      var cobyla = new Cobyla(f, constraints); 
      bool success = cobyla.Minimize(); 
      double minimum = cobyla.Value; 
      double[] solution = cobyla.Solution; 
     } 
    } 
+1

ん「サイクルを使用しては、」特別な何かを意味しますか? (明らかに、過去に多くの人が行ったように、行列乗算をループで書くことができます...私はあなたが別の何かを必要とすると思いますが、それが何であるかは明らかではありません) –

答えて

4

あなたのコード例に示しラムダ式は次のように書き換えることができます。そして、

double ApplyMatrix(double[,] matrix, double[] x) 
{ 
    double sum = 0; 

    for (int row = 0; row < matrix.GetLength(1); row++) 
    { 
     double rowSum = 0; 

     for (int col = 0; col < matrix.GetLength(0); col++) 
     { 
      rowSum += matrix[col, row] * x[col]; 
     } 

     sum += x[row] * rowSum; 
    } 

    return sum; 
} 

、あなたは上記を使用していますNonlinearObjectiveFunctionにラムダ式を渡すことができます。

var f = new NonlinearObjectiveFunction(3, x => ApplyMatrix(Matrix, x)); 

これは、もちろん、あなたのメソッドに渡されたユーザー定義Matrixのとx配列の次元が一貫のwiであると仮定していますお互いに。私。ユーザ定義の行列は常に正方形であり、x配列には、少なくともユーザ定義行列の行と列の要素数と同じ数の要素があります。

あなたが質問しているのではない場合は、の意味の説明を含めて、達成しようとしている内容をより正確に説明してください。

関連する問題