Skip to content

Commit 6b0ea89

Browse files
committed
feat: implement broadcastSizes and broadcastTo functions for matrix operations
1 parent 4bbe862 commit 6b0ea89

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { broadcastSizes } from '../../utils/array.js'
2+
import { factory } from '../../utils/factory.js'
3+
import { isMatrix } from '../../utils/is.js'
4+
5+
const name = 'broadcastSizes'
6+
const dependencies = ['typed']
7+
8+
export const createBroadcastSizes = /* #__PURE__ */ factory(name, dependencies, ({ typed }) => {
9+
/**
10+
* Calculate the broadcasted size of one or more matrices or arrays.
11+
* Always returns an Array containing numbers.
12+
*
13+
* Syntax:
14+
*
15+
* math.broadcastSizes(x, y)
16+
* math.broadcastSizes(x, y, ...)
17+
*
18+
* Examples:
19+
*
20+
* math.broadcastSizes([2, 3]) // returns [2, 3]
21+
* math.broadcastSizes([2, 3], [3]) // returns [2, 3]
22+
* math.broadcastSizes([1, 2, 3], [[1, 2, 3]]) // returns [[1, 2, 3]]
23+
*
24+
* See also:
25+
*
26+
* size, reshape, squeeze, broadcastTo
27+
*
28+
* @param {...(Array|Matrix)} x One or more matrices or arrays
29+
* @return {Array} A vector with the broadcasted size.
30+
*/
31+
return typed(name, {
32+
'...Array': broadcastSizes,
33+
'...Matrix': matrices => broadcastSizes(...matrices.map(m => m.toArray())),
34+
'...Array|Matrix': collections => broadcastSizes(...collections.map(c => isMatrix(c) ? c.toArray() : c))
35+
})
36+
})

src/function/matrix/broadcastTo.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { broadcastTo } from '../../utils/array.js'
2+
import { factory } from '../../utils/factory.js'
3+
4+
const name = 'broadcastTo'
5+
const dependencies = ['typed']
6+
7+
export const createBroadcastTo = /* #__PURE__ */ factory(name, dependencies, ({ typed }) => {
8+
/**
9+
* Broadcast an array to a specified size.
10+
*
11+
* Syntax:
12+
*
13+
* math.broadcastTo(x, size)
14+
*
15+
* Examples:
16+
*
17+
* math.broadcastTo([1, 2, 3], [2, 3]) // returns [[1, 2, 3], [1, 2, 3]]
18+
* math.broadcastTo([2, 3], [2, 2]) // returns [[2, 3], [2, 3]]
19+
*
20+
* See also:
21+
*
22+
* size, reshape, squeeze, broadcastSizes
23+
*
24+
* @param {Array|Matrix} x The array or matrix to broadcast
25+
* @param {Array|Matrix} size The target size
26+
* @return {Array} The broadcasted array
27+
*/
28+
return typed(name, {
29+
'Array, Array': broadcastTo,
30+
'Array, Matrix': (arr, size) => broadcastTo(arr, size.toArray()),
31+
'Matrix, Array': (M, size) => M.create(broadcastTo(M.toArray(), size)),
32+
'Matrix, Matrix': (M1, size) => M1.create(broadcastTo(M1.toArray(), size.toArray()))
33+
})
34+
})

0 commit comments

Comments
 (0)