Tuesday, January 18, 2011

LU Decomposition C Code

The goal of this project is to code the LU Decomposition in C. This simple program finds the L and U factorization of an NxN matrix.

Below are links to the documentation and code
Latex pdf
LU.c
Latex source

1 comment:

  1. #include

    using namespace std;

    int main()
    {
    float a[4][5];
    float l[4][4];
    float u[4][4];
    float v[4][2];
    float x, y, z;

    for (int i = 1; i < 4; i++) {
    for (int j = 1; j < 5; j++) {
    cin >> a[i][j];
    }
    }

    u[1][1] = a[1][1];
    u[1][2] = a[1][2];
    u[1][3] = a[1][3];
    l[2][1] = a[2][1] / a[1][1];
    l[3][1] = a[3][1] / a[1][1];
    l[3][2] = (a[3][2] - ((a[3][1] * a[1][2]) / a[1][1])) / (a[2][2] - ((a[2][1] * a[1][2]) / a[1][1]));
    u[2][2] = a[2][2] - ((a[2][1] * a[1][2]) / a[1][1]);
    u[2][3] = a[2][3] - ((a[2][1] * a[1][3]) / a[1][1]);

    u[3][3] = a[3][3] - ((a[3][1] * a[1][3]) / a[1][1]) - (l[3][2] * u[2][3]);

    u[2][1] = u[3][1] = u[3][2] = 0;
    l[1][1] = l[2][2] = l[3][3] = 1;
    l[1][2] = l[1][3] = l[2][3] = 0;

    cout << endl;
    cout << "L matrix : " << endl;
    for (int i = 1; i < 4; i++) {
    for (int j = 1; j < 4; j++) {
    cout << l[i][j] << " ";
    }
    cout << endl;
    }

    cout << endl;
    cout << "U matrix : " << endl;
    for (int i = 1; i < 4; i++) {
    for (int j = 1; j < 4; j++) {
    cout << u[i][j] << " ";
    }
    cout << endl;
    }

    v[1][1] = a[1][4];
    v[2][1] = a[2][4] - (v[1][1] * l[2][1]);
    v[3][1] = a[3][4] - (v[1][1] * l[3][1]) - (v[2][2] * l[3][2]);

    z = v[3][1] / u[3][3];
    y = (v[2][1] - (u[2][3] * z)) / u[2][2];
    x = (v[1][1] - (u[1][3] * z) - (u[1][2] * y)) / u[1][1];

    cout << endl;
    cout << "Solution : " << endl;
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    cout << "z = " << z << endl;

    return 0;
    }

    ReplyDelete