Public
Edited
Jul 10, 2024
Importers
Insert cell
Insert cell
Insert cell
function choleskyDecomposition(matrix) {
// Argument "matrix" can be either math.matrix or standard 2D array
const A = math.matrix(matrix);
// Matrix A must be symmetric
console.assert(math.deepEqual(A, math.transpose(A)));

const n = A.size()[0];
// Prepare 2D array with 0
const L = new Array(n).fill(0).map(_ => new Array(n).fill(0));

d3.range(n).forEach(i => {
d3.range(i+1).forEach(k => {
const s = d3.sum(d3.range(k).map(j => L[i][j]*L[k][j]));
L[i][k] = i === k ? math.sqrt(A.get([k, k]) - s) : 1/L[k][k] * (A.get([i, k]) - s);
})
});
return L;
}
Insert cell
cholesky2 = function (array) {
const zeros = [...Array(array.length)].map((_) =>
Array(array.length).fill(0)
);
const L = zeros.map((row, r, xL) =>
row.map((v, c) => {
const sum = row.reduce(
(s, _, i) => (i < c ? s + xL[r][i] * xL[c][i] : s),
0
);
return (xL[r][c] =
c < r + 1
? r === c
? Math.sqrt(array[r][r] - sum)
: (array[r][c] - sum) / xL[c][c]
: v);
})
);
return L;
}
Insert cell
Insert cell
{
const m1 = [
[25, 15, -5],
[15, 18, 0],
[-5, 0, 11]
];
return cholesky2(m1);
// It is also OK to pass matrix like below
// choleskyDecomposition(math.matrix(m1));
}
Insert cell
{
const m1 = [[25, 15, -5],
[15, 18, 0],
[-5, 0, 11]];
return choleskyDecomposition(m1);
// It is also OK to pass matrix like below
// choleskyDecomposition(math.matrix(m1));
}
Insert cell
{
const m2 = [[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]];
return choleskyDecomposition(m2);
}
Insert cell
{
const m2 = [
[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]
];
return cholesky2(m2);
}
Insert cell
// Check if LL^T is equal to original matrix
{
const m1 = [[25, 15, -5],
[15, 18, 0],
[-5, 0, 11]];
const m2 = [[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]];
const L1 = choleskyDecomposition(m1);
const L2 = choleskyDecomposition(m2);
return [
math.deepEqual(m1, math.multiply(L1, math.transpose(L1))),
math.deepEqual(m2, math.multiply(L2, math.transpose(L2))),
];
}
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more