Facebook
From cjoyales, 3 Years ago, written in JavaScript.
Embed
Download Paste or View Raw
Hits: 129
  1. // matrix A
  2. let matrixA = [
  3.   [6, -2, -3],
  4.   [-2, 5, -2],
  5.   [-3, -2, 8],
  6. ];
  7.  
  8.  
  9. // Generate L and U using matrix A length
  10. let matrixL = Array(matrixA.length)
  11.   .fill()
  12.   .map(() => Array(matrixA.length).fill(0));
  13. let matrixU = Array(matrixA.length)
  14.   .fill()
  15.   .map(() => Array(matrixA.length).fill(0));
  16.  
  17. crout = () => {
  18.   // assign matrix A length to a variable
  19.   let n = matrixA.length;
  20.  
  21.   // loop in to index
  22.   for (i = 0; i < n; i++) {
  23.     for (j = 0; j < n; j++) {
  24.       // if j is less than i change value of matrixL to 0 with its corresponding indexes
  25.       if (j < i) matrixL[j][i] = 0;
  26.  
  27.       else {
  28.         // the first column of matrix L is equal to the first column of matrix A
  29.         matrixL[j][i] = matrixA[j][i];
  30.         //  loop the values excluding the first column and top row
  31.         for (k = 0; k < i; k++) {
  32.           matrixL[j][i] = matrixL[j][i] - matrixL[j][k] * matrixU[k][i];
  33.         }
  34.       }
  35.     }
  36.     // loop in to index
  37.     for (j = 0; j < n; j++) {
  38.       // if j is less than i change value of martixU to 0 with its corresponding indexes
  39.       if (j < i) matrixU[i][j] = 0;
  40.       // if j is equal to i the change value to 1
  41.       //  result to a diagonal values of 1
  42.       else if (j == i) matrixU[i][j] = 1;
  43.  
  44.       else {
  45.         // get index of the first rows of matrixU
  46.         matrixU[i][j] = matrixA[i][j] / matrixL[i][i];
  47.         // loop to get values excluding the first rows, 1's and 0's
  48.         for (k = 0; k < i; k++) {
  49.           matrixU[i][j] =
  50.             matrixU[i][j] - (matrixL[i][k] * matrixU[k][j]) / matrixL[i][i];
  51.         }
  52.       }
  53.     }
  54.   }
  55.   //  print in console
  56.   console.log("matrixA:\n", matrixA, "\n\nmatrixL:\n", matrixL, "\n\nmatrixU:\n", matrixU);
  57.  
  58. };
  59. crout();

Replies to crout's method javascript rss

Title Name Language When
Re: crout's method javascript cjoyales javascript 3 Years ago.