Skip to content

Commit

Permalink
Implement matrix transposition
Browse files Browse the repository at this point in the history
  • Loading branch information
frostburn committed May 2, 2024
1 parent 5141f00 commit 5fcae80
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
3 changes: 3 additions & 0 deletions documentation/BUILTIN.md
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,9 @@ Attach a tracking ID to the interval.
### trackingIds(*interval*)
Obtain an array of the tracking IDs attached to the interval.

### transpose(*matrix*)
Transpose a matrix. For modal transposition see rotate().

### trunc(*interval*)
Truncate value towards zero to the nearest integer.

Expand Down
8 changes: 8 additions & 0 deletions src/parser/__tests__/vector-broadcasting.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -481,4 +481,12 @@ describe('SonicWeave vector broadcasting', () => {
],
]);
});

it('can transpose a matrix', () => {
const mat = sw2D`transpose([[1, 2], [3, 4], [5, 6]])`;
expect(mat).toEqual([
[1, 3, 5],
[2, 4, 6],
]);
});
});
22 changes: 22 additions & 0 deletions src/stdlib/builtin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1631,6 +1631,27 @@ valFromPrimeArray.__doc__ =
'Convert an array of prime mapping entries to a val.';
valFromPrimeArray.__node__ = builtinNode(valFromPrimeArray);

function transpose(matrix: SonicWeaveValue[][]) {
if (!Array.isArray(matrix)) {
return matrix;
}
if (!Array.isArray(matrix[0])) {
return [...matrix];
}
const width = matrix.reduce((w, row) => Math.max(w, row.length), 0);
const result: SonicWeaveValue[][] = [];
for (let i = 0; i < width; ++i) {
const row: SonicWeaveValue[] = [];
for (let j = 0; j < matrix.length; ++j) {
row.push(matrix[j][i] ?? fromInteger(0));
}
result.push(row);
}
return result;
}
transpose.__doc__ = 'Transpose a matrix. For modal transposition see rotate().';
transpose.__node__ = builtinNode(transpose);

function hasConstantStructure_(this: ExpressionVisitor, scale?: Interval[]) {
scale ??= this.currentScale;
this.spendGas(scale.length * scale.length);
Expand Down Expand Up @@ -2508,6 +2529,7 @@ export const BUILTIN_CONTEXT: Record<string, Interval | SonicWeaveFunction> = {
toPrimeArray,
monzoFromPrimeArray,
valFromPrimeArray,
transpose,
hasConstantStructure: hasConstantStructure_,
stepString: stepString_,
str,
Expand Down

0 comments on commit 5fcae80

Please sign in to comment.