Here's a simple approach to find the lower triangular matrix of a given matrix in JavaScript using nested loops:
index.tsx
// Define the matrixconst matrix = [
[1, 0, 0, 0],
[2, 3, 0, 0],
[4, 5, 6, 0],
[7, 8, 9, 10]
];
// Get the number of rows/columns in the matrixconst n = matrix.length;
// Initialize an empty lower triangular matrixconst lowerTriangularMatrix = [];
// Loop through each row of the matrixfor (let i = 0; i < n; i++) {
// Initialize an empty row for the lower triangular matrixconst row = [];
// Loop through each column of the matrixfor (let j = 0; j < n; j++) {
// If we're on or above the diagonal, the value is zeroif (i < j) {
row.push(0);
}
// Otherwise, copy the value from the original matrixelse {
row.push(matrix[i][j]);
}
}
// Add the row to the lowerTriangularMatrix lowerTriangularMatrix.push(row);
}
// Print the lower triangular matrixconsole.log(lowerTriangularMatrix);
860 chars
38 lines
This will output the following lower triangular matrix: