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