|
| 1 | +import { factory } from '../../utils/factory.js' |
| 2 | +const name = 'corr' |
| 3 | +const dependencies = ['typed', 'matrix', 'mean', 'sqrt', 'sum', 'add', 'subtract', 'multiply', 'pow', 'divide'] |
| 4 | + |
| 5 | +export const createCorr = /* #__PURE__ */ factory(name, dependencies, ({ typed, matrix, sqrt, sum, add, subtract, multiply, pow, divide }) => { |
| 6 | + /** |
| 7 | + * Compute the correlation coefficient of a two list with values, For matrices, the matrix correlation coefficient is calculated. |
| 8 | + * |
| 9 | + * Syntax: |
| 10 | + * |
| 11 | + * math.corr(A, B) |
| 12 | + * |
| 13 | + * Examples: |
| 14 | + * |
| 15 | + * math.corr([1, 2, 3, 4, 5], [4, 5, 6, 7, 8]) // returns 1 |
| 16 | + * math.corr([1, 2.2, 3, 4.8, 5], [4, 5.3, 6.6, 7, 8]) // returns 0.9569941688503644 |
| 17 | + * math.corr(math.matrix([[1, 2.2, 3, 4.8, 5], [1, 2, 3, 4, 5]]), math.matrix([[4, 5.3, 6.6, 7, 8], [1, 2, 3, 4, 5]])) // returns DenseMatrix [0.9569941688503644, 1] |
| 18 | + * |
| 19 | + * See also: |
| 20 | + * |
| 21 | + * median, mean, min, max, sum, prod, std, variance |
| 22 | + * |
| 23 | + * @param {Array | Matrix} A The first array or matrix to compute correlation coefficient |
| 24 | + * @param {Array | Matrix} B The second array or matrix to compute correlation coefficient |
| 25 | + * @return {*} The correlation coefficient |
| 26 | + */ |
| 27 | + return typed(name, { |
| 28 | + 'Array, Array': function (A, B) { |
| 29 | + return _corr(A, B) |
| 30 | + }, |
| 31 | + 'Matrix, Matrix': function (xMatrix, yMatrix) { |
| 32 | + return matrix(_corr(xMatrix.toArray(), yMatrix.toArray())) |
| 33 | + } |
| 34 | + }) |
| 35 | + /** |
| 36 | + * Calculate the correlation coefficient between two arrays or matrices. |
| 37 | + * @param {Array | Matrix} A |
| 38 | + * @param {Array | Matrix} B |
| 39 | + * @return {*} correlation coefficient |
| 40 | + * @private |
| 41 | + */ |
| 42 | + function _corr (A, B) { |
| 43 | + if (Array.isArray(A[0]) && Array.isArray(B[0])) { |
| 44 | + const correlations = [] |
| 45 | + for (let i = 0; i < A.length; i++) { |
| 46 | + correlations.push(correlation(A[i], B[i])) |
| 47 | + } |
| 48 | + return correlations |
| 49 | + } else { |
| 50 | + return correlation(A, B) |
| 51 | + } |
| 52 | + } |
| 53 | + function correlation (A, B) { |
| 54 | + const n = A.length |
| 55 | + const sumX = sum(A) |
| 56 | + const sumY = sum(B) |
| 57 | + const sumXY = A.reduce((acc, x, index) => add(acc, multiply(x, B[index])), 0) |
| 58 | + const sumXSquare = sum(A.map(x => pow(x, 2))) |
| 59 | + const sumYSquare = sum(B.map(y => pow(y, 2))) |
| 60 | + const numerator = subtract(multiply(n, sumXY), multiply(sumX, sumY)) |
| 61 | + const denominator = sqrt(multiply(subtract(multiply(n, sumXSquare), pow(sumX, 2)), subtract(multiply(n, sumYSquare), pow(sumY, 2)))) |
| 62 | + return divide(numerator, denominator) |
| 63 | + } |
| 64 | +}) |
0 commit comments