transform to orthognal matrix in javascript

An orthogonal matrix is a type of square matrix whose columns and rows are orthogonal unit vectors (orthonormal vectors). The formula to transform a given square matrix to an orthogonal matrix is known as the Gram-Schmidt Process. Here is an implementation of Gram-Schmidt Process in Javascript:

index.tsx
function toOrthogonal(matrix) {
  const n = matrix.length;
  // Copy the input matrix
  const Q = matrix.map(row => [...row])
  // Iterate over columns
  for (let j = 0; j < n; j++) {
    // Iterate over previous columns
    for (let i = 0; i < j; i++) {
      let dot = 0;
      // Calculate the dot product
      for (let k = 0; k < n; k++) {
        dot += Q[k][i] * Q[k][j];
      }
      // Subtract the projection
      for (let k = 0; k < n; k++) {
        Q[k][j] -= dot * Q[k][i];
      }
    }
    // Normalize the column
    let norm = 0;
    for (let k = 0; k < n; k++) {
      norm += Q[k][j] ** 2;
    }
    norm = Math.sqrt(norm);
    if (norm === 0) {
      throw new Error("Cannot orthogonalize matrix with zero columns");
    }
    for (let k = 0; k < n; k++) {
      Q[k][j] /= norm;
    }
  }
  return Q;
}
827 chars
34 lines

This function takes a square matrix as input and returns an orthogonal matrix. If the input matrix has zero columns, an error is thrown. Otherwise, each column of the input matrix is orthogonalized using the Gram-Schmidt Process.

gistlibby LogSnag