als-statistics
Version:
Modular JS statistics toolkit for Node.js and the browser: descriptive stats, correlations (Pearson/Spearman/Kendall), t-tests & ANOVA (Student/Welch), reliability (Cronbach’s alpha), regression (linear/logistic), clustering (DBSCAN/HDBSCAN), and table/co
49 lines (44 loc) • 1.67 kB
JavaScript
const MatrixUtils = {
transpose (arr){ return (arr && arr.length) ? arr[0].map((_, i) => arr.map(row => row[i])) : [] },
// transpose(A) { return A[0].map((_, i) => A.map(row => row[i])) },
multiply(A, B) {
const result = Array.from({ length: A.length }, () => Array(B[0].length).fill(0));
for (let i = 0; i < A.length; i++) {
for (let j = 0; j < B[0].length; j++) {
for (let k = 0; k < B.length; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
return result;
},
multiplyVec(A, b) {
return A.map(row => row.reduce((acc, aij, j) => acc + aij * b[j], 0));
},
inverse(A) {
const EPS = 3e-14;
const n = A.length;
const I = Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => (i === j ? 1 : 0)));
const AI = A.map((row, i) => [...row, ...I[i]]);
for (let i = 0; i < n; i++) {
let maxRow = i;
for (let k = i + 1; k < n; k++) {
if (Math.abs(AI[k][i]) > Math.abs(AI[maxRow][i])) maxRow = k;
}
[AI[i], AI[maxRow]] = [AI[maxRow], AI[i]];
const diag = AI[i][i];
for (let j = 0; j < 2 * n; j++) {
if (Math.abs(diag) < EPS) throw new Error('singular matrix');
AI[i][j] /= diag;
}
for (let k = 0; k < n; k++) {
if (k !== i) {
const factor = AI[k][i];
for (let j = 0; j < 2 * n; j++) AI[k][j] -= factor * AI[i][j];
}
}
}
return AI.map(row => row.slice(n));
}
};
export default MatrixUtils