Public
Edited
Jul 20, 2024
Insert cell
Insert cell
test = svd(math.matrix(a))
Insert cell
Insert cell
SVDJS.SVD(a)
Insert cell
function argSort(a) {
const b = a.map((x, i) => [i, x]);
b.sort((a, b) => (a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : 0));
return b.map((x) => x[0]);
}
Insert cell
function svd(matrix, tol = 1e-10) {
const A = matrix;
const size = math.size(A);
const m = size._data[0];
const n = size._data[1];
const U = math.zeros(m, m);
const S = math.zeros(m, n);
const V = math.zeros(n, n);

// Step 1: Calculate A^T * A and A * A^T
const ATA = math.multiply(math.transpose(A), A);
const AAT = math.multiply(A, math.transpose(A));

// Step 2: Calculate the eigenvalues and eigenvectors of A^T * A
const eigen = math.eigs(ATA);

//Step 3: Sort eigenvalues and rearrange eigenvectors
const sorted_indices = [...new Set(argSort(eigen.values.toArray()).reverse())];
const eigenvalues = eigen.values.subset(math.index(sorted_indices));
const eigenvectors = sorted_indices.map(i => eigen.eigenvectors[i].value);

// Step 4: Calculate singular values and the pseudoinverse of S
const singular_values = math.map(eigenvalues, math.sqrt);
const non_zero_singular_values = math.map(singular_values, x => math.larger(x, tol));
const r = math.sum(non_zero_singular_values.map(x => x !== 0 ? 1 : 0));
// it seems to work up to here

return math.range(1,r)
S.subset(
math.index(math.range(1, r), math.range(1, r)),
math.diag(singular_values.subset(math.index(non_zero_singular_values)))
);
return {eigenvalues, eigenvectors}
const S_pseudo_inverse = math.pinv(S);
// Step 5: Calculate U and V
U.subset(
[":", `:{r}`],
math.multiply(A, eigenvectors.subset([":", `:{r}`]))
);

V.subset([":", `:{r}`], eigenvectors.subset([":", `:{r}`]));
return { U, S, V };
}
Insert cell
math.version
Insert cell
math = require("mathjs@13.0.3")
Insert cell
SVDJS = require("svd-js")
Insert cell
a = [[1,2],[10,8]]
Insert cell
result = SVDJS.SVD(a)
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