Home Reference Source Repository

src/diag.js

  1. /**
  2. * Create diagonal matrix from vector
  3. *
  4. * @param {Array} d
  5. * @returns {Array}
  6. * @example
  7. *
  8. * diag([1, 2])
  9. * // [[1, 0],
  10. * // [0, 2]]
  11. */
  12. export default function diag (d) {
  13. var i, i1, j, n = d.length, A = Array(n), Ai
  14. for (i = n - 1; i >= 0; i--) {
  15. Ai = Array(n)
  16. i1 = i + 2
  17. for (j = n - 1; j >= i1; j -= 2) {
  18. Ai[j] = 0
  19. Ai[j - 1] = 0
  20. }
  21. if (j > i) { Ai[j] = 0; }
  22. Ai[i] = d[i]
  23. for (j = i - 1; j >= 1; j -= 2) {
  24. Ai[j] = 0
  25. Ai[j - 1] = 0
  26. }
  27. if (j === 0) { Ai[0] = 0; }
  28. A[i] = Ai
  29. }
  30. return A
  31. }