matrixFromColumns.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { factory } from '../../utils/factory.js';
  2. var name = 'matrixFromColumns';
  3. var dependencies = ['typed', 'matrix', 'flatten', 'size'];
  4. export var createMatrixFromColumns = /* #__PURE__ */factory(name, dependencies, _ref => {
  5. var {
  6. typed,
  7. matrix,
  8. flatten,
  9. size
  10. } = _ref;
  11. /**
  12. * Create a dense matrix from vectors as individual columns.
  13. * If you pass row vectors, they will be transposed (but not conjugated!)
  14. *
  15. * Syntax:
  16. *
  17. * math.matrixFromColumns(...arr)
  18. * math.matrixFromColumns(col1, col2)
  19. * math.matrixFromColumns(col1, col2, col3)
  20. *
  21. * Examples:
  22. *
  23. * math.matrixFromColumns([1, 2, 3], [[4],[5],[6]])
  24. * math.matrixFromColumns(...vectors)
  25. *
  26. * See also:
  27. *
  28. * matrix, matrixFromRows, matrixFromFunction, zeros
  29. *
  30. * @param {... Array | Matrix} cols Multiple columns
  31. * @return { number[][] | Matrix } if at least one of the arguments is an array, an array will be returned
  32. */
  33. return typed(name, {
  34. '...Array': function Array(arr) {
  35. return _createArray(arr);
  36. },
  37. '...Matrix': function Matrix(arr) {
  38. return matrix(_createArray(arr.map(m => m.toArray())));
  39. }
  40. // TODO implement this properly for SparseMatrix
  41. });
  42. function _createArray(arr) {
  43. if (arr.length === 0) throw new TypeError('At least one column is needed to construct a matrix.');
  44. var N = checkVectorTypeAndReturnLength(arr[0]);
  45. // create an array with empty rows
  46. var result = [];
  47. for (var i = 0; i < N; i++) {
  48. result[i] = [];
  49. }
  50. // loop columns
  51. for (var col of arr) {
  52. var colLength = checkVectorTypeAndReturnLength(col);
  53. if (colLength !== N) {
  54. throw new TypeError('The vectors had different length: ' + (N | 0) + ' ≠ ' + (colLength | 0));
  55. }
  56. var f = flatten(col);
  57. // push a value to each row
  58. for (var _i = 0; _i < N; _i++) {
  59. result[_i].push(f[_i]);
  60. }
  61. }
  62. return result;
  63. }
  64. function checkVectorTypeAndReturnLength(vec) {
  65. var s = size(vec);
  66. if (s.length === 1) {
  67. // 1D vector
  68. return s[0];
  69. } else if (s.length === 2) {
  70. // 2D vector
  71. if (s[0] === 1) {
  72. // row vector
  73. return s[1];
  74. } else if (s[1] === 1) {
  75. // col vector
  76. return s[0];
  77. } else {
  78. throw new TypeError('At least one of the arguments is not a vector.');
  79. }
  80. } else {
  81. throw new TypeError('Only one- or two-dimensional vectors are supported.');
  82. }
  83. }
  84. });