Lapack Java SGBTRF and SGBTRS

A sample code in Java, as a memo of the correct indexing (row/col):

import org.netlib.lapack.Sgbtrf;
import org.netlib.lapack.Sgbtrs;
  /*
  Purpose:
    We want to use the LAPACK routines SGBTRF and SGBTRS to solve a banded 
    linear system of the form A*x=b.  Our 4x4 version of this problem is:

      2.0 -1.0  0.0  0.0   x(0)      0.0
     -1.0  2.0 -1.0  0.0 * x(1)  =   0.0
      0.0 -1.0  2.0 -1.0   x(2)      0.0
      0.0  0.0 -1.0  2.0   x(3)      5.0

    The solution is x = ( 1, 2, 3, 4 ).
  */
  public static void main(String[] args) {
    int n = 4;
    int m = 2;
    int k = 1; // kl = ku
    float[] AB = { 0, 0, 2, -1, //
        0, -1, 2, -1,//
        0, -1, 2, -1, //
        0, -1, 2, 0 }; // new float[(3 * k + 1)*n];
    float[] B = { 0, 0, 0, 5, 0, 0, 0, 5 }; //new float[n*m];
    int[] IPIV = new int[n];
    intW info = new intW(0);

    Sgbtrf.sgbtrf(n, n, k, k, AB, 0, 3 * k + 1, IPIV, 0, info);
    System.out.println("Info = " + info.val);

    Sgbtrs.sgbtrs("N", n, k, k, m, AB, 0, 3 * k + 1, IPIV, 0, B, 0, n, info);
    System.out.println("Info = " + info.val);
    System.out.println("Solution: " + Arrays.toString(B));

    n = 10;
    m = 2;
    k = 3;
    AB = new float[(3 * k + 1) * n];
    B = new float[n * m];
    IPIV = new int[n];
    for (int i = 0; i < n; i++) {
      for (int j = Math.max(0, i - k); j <= i; j++) {
        if (i == j) {
          AB[k * 2 + i - j + j * (3 * k + 1)] = 2;
        } else if (i == j + 1 || i == j - 1) {
          AB[k * 2 + i - j + j * (3 * k + 1)] = -1;
        }
      }
    }
    for (int i = 0; i < n; i++) {
      for (int j = Math.max(0, i - k); j < i; j++) {
        AB[k * 2 + j - i + i * (3 * k + 1)] = AB[k * 2 + i - j + j * (3 * k + 1)];
      }
    }
    System.out.println("AB: " + Arrays.toString(AB));
    for (int i = 0; i < m; i++) {
      B[(i + 1) * n - 1] = n + 1;
    }

    Sgbtrf.sgbtrf(n, n, k, k, AB, 0, 3 * k + 1, IPIV, 0, info);
    System.out.println("Info = " + info.val);

    Sgbtrs.sgbtrs("N", n, k, k, m, AB, 0, 3 * k + 1, IPIV, 0, B, 0, n, info);
    System.out.println("Info = " + info.val);
    System.out.println("Solution: " + Arrays.toString(B));
  }
This entry was posted in programming. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *