matrixFromRows.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { factory } from '../../utils/factory.js';
  2. var name = 'matrixFromRows';
  3. var dependencies = ['typed', 'matrix', 'flatten', 'size'];
  4. export var createMatrixFromRows = /* #__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 rows.
  13. * If you pass column vectors, they will be transposed (but not conjugated!)
  14. *
  15. * Syntax:
  16. *
  17. * math.matrixFromRows(...arr)
  18. * math.matrixFromRows(row1, row2)
  19. * math.matrixFromRows(row1, row2, row3)
  20. *
  21. * Examples:
  22. *
  23. * math.matrixFromRows([1, 2, 3], [[4],[5],[6]])
  24. * math.matrixFromRows(...vectors)
  25. *
  26. * See also:
  27. *
  28. * matrix, matrixFromColumns, matrixFromFunction, zeros
  29. *
  30. * @param {... Array | Matrix} rows Multiple rows
  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 row is needed to construct a matrix.');
  44. var N = checkVectorTypeAndReturnLength(arr[0]);
  45. var result = [];
  46. for (var row of arr) {
  47. var rowLength = checkVectorTypeAndReturnLength(row);
  48. if (rowLength !== N) {
  49. throw new TypeError('The vectors had different length: ' + (N | 0) + ' ≠ ' + (rowLength | 0));
  50. }
  51. result.push(flatten(row));
  52. }
  53. return result;
  54. }
  55. function checkVectorTypeAndReturnLength(vec) {
  56. var s = size(vec);
  57. if (s.length === 1) {
  58. // 1D vector
  59. return s[0];
  60. } else if (s.length === 2) {
  61. // 2D vector
  62. if (s[0] === 1) {
  63. // row vector
  64. return s[1];
  65. } else if (s[1] === 1) {
  66. // col vector
  67. return s[0];
  68. } else {
  69. throw new TypeError('At least one of the arguments is not a vector.');
  70. }
  71. } else {
  72. throw new TypeError('Only one- or two-dimensional vectors are supported.');
  73. }
  74. }
  75. });