Skip to content

Commit 02b39b4

Browse files
headlessNodekgryte
andauthored
feat: add ndarray/diagonal
PR-URL: #11900 Co-authored-by: Athan Reines <kgryte@gmail.com> Reviewed-by: Athan Reines <kgryte@gmail.com> Closes: stdlib-js/metr-issue-tracker#497
1 parent 60188d9 commit 02b39b4

10 files changed

Lines changed: 1495 additions & 0 deletions

File tree

Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
<!--
2+
3+
@license Apache-2.0
4+
5+
Copyright (c) 2026 The Stdlib Authors.
6+
7+
Licensed under the Apache License, Version 2.0 (the "License");
8+
you may not use this file except in compliance with the License.
9+
You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
19+
-->
20+
21+
# diagonal
22+
23+
> Return a **read-only** view of the diagonal of a matrix (or stack of matrices).
24+
25+
<!-- Section to include introductory text. Make sure to keep an empty line after the intro section element. -->
26+
27+
<section class="intro">
28+
29+
For an `M`-by-`N` matrix `A`, the `k`-th diagonal is defined as
30+
31+
<!-- <equation class="equation" label="eq:diagonal_definition" align="center" raw="D_k = \{\, A_{i,j} : j - i = k \,\}" alt="Definition of the k-th diagonal of a matrix."> -->
32+
33+
```math
34+
D_k = \{\, A_{i,j} : j - i = k \,\}
35+
```
36+
37+
<!-- <div class="equation" align="center" data-raw-text="D_k = \{\, A_{i,j} : j - i = k \,\}" data-equation="eq:diagonal_definition">
38+
<img src="" alt="Definition of the k-th diagonal of a matrix.">
39+
<br>
40+
</div> -->
41+
42+
<!-- </equation> -->
43+
44+
where `k = 0` corresponds to the main diagonal, `k > 0` corresponds to the super-diagonals (above the main diagonal), and `k < 0` corresponds to the sub-diagonals (below the main diagonal). For example, given the matrix
45+
46+
<!-- <equation class="equation" label="eq:diagonal_example" align="center" raw="A = \begin{bmatrix} a_{0,0} & a_{0,1} & a_{0,2} \\ a_{1,0} & a_{1,1} & a_{1,2} \\ a_{2,0} & a_{2,1} & a_{2,2} \end{bmatrix}" alt="Example matrix."> -->
47+
48+
```math
49+
A = \begin{bmatrix} a_{0,0} & a_{0,1} & a_{0,2} \\ a_{1,0} & a_{1,1} & a_{1,2} \\ a_{2,0} & a_{2,1} & a_{2,2} \end{bmatrix}
50+
```
51+
52+
<!-- <div class="equation" align="center" data-raw-text="A = \begin{bmatrix} a_{0,0} & a_{0,1} & a_{0,2} \\ a_{1,0} & a_{1,1} & a_{1,2} \\ a_{2,0} & a_{2,1} & a_{2,2} \end{bmatrix}" data-equation="eq:diagonal_example">
53+
<img src="" alt="Example matrix.">
54+
<br>
55+
</div> -->
56+
57+
<!-- </equation> -->
58+
59+
the main diagonal is `[ a_{0,0}, a_{1,1}, a_{2,2} ]`, the super-diagonal `k = 1` is `[ a_{0,1}, a_{1,2} ]`, and the sub-diagonal `k = -1` is `[ a_{1,0}, a_{2,1} ]`.
60+
61+
</section>
62+
63+
<!-- /.intro -->
64+
65+
<!-- Package usage documentation. -->
66+
67+
<section class="usage">
68+
69+
## Usage
70+
71+
```javascript
72+
var diagonal = require( '@stdlib/ndarray/diagonal' );
73+
```
74+
75+
#### diagonal( x\[, options] )
76+
77+
Returns a read-only view of the diagonal of a matrix (or stack of matrices).
78+
79+
```javascript
80+
var array = require( '@stdlib/ndarray/array' );
81+
82+
var x = array( [ [ 1.0, 2.0, 3.0 ], [ 4.0, 5.0, 6.0 ], [ 7.0, 8.0, 9.0 ] ] );
83+
// returns <ndarray>[ [ 1.0, 2.0, 3.0 ], [ 4.0, 5.0, 6.0 ], [ 7.0, 8.0, 9.0 ] ]
84+
85+
var y = diagonal( x );
86+
// returns <ndarray>[ 1.0, 5.0, 9.0 ]
87+
```
88+
89+
The function accepts the following arguments:
90+
91+
- **x**: input [`ndarray`][@stdlib/ndarray/ctor].
92+
- **options**: function options.
93+
94+
The function accepts the following options:
95+
96+
- **k**: diagonal offset. The diagonal offset is interpreted as `column - row`. Accordingly, when `k = 0`, the function returns the main diagonal; when `k > 0`, the function returns the diagonal above the main diagonal; and when `k < 0`, the function returns the diagonal below the main diagonal. Default: `0`.
97+
- **dims**: dimension indices defining the plane from which to extract the diagonal. Must contain exactly two unique dimension indices. The first element specifies the row-like dimension. The second element specifies the column-like dimension. If a dimension index is provided as an integer less than zero, the dimension index is resolved relative to the last dimension, with the last dimension corresponding to the value `-1`. Default: `[-2, -1]`.
98+
99+
</section>
100+
101+
<!-- /.usage -->
102+
103+
<!-- Package usage notes. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
104+
105+
<section class="notes">
106+
107+
## Notes
108+
109+
- The order of the dimension indices contained in `options.dims` matters. The first element specifies the row-like dimension. The second element specifies the column-like dimension.
110+
- Each provided dimension index must reside on the interval `[-ndims, ndims-1]`.
111+
112+
</section>
113+
114+
<!-- /.notes -->
115+
116+
<!-- Package usage examples. -->
117+
118+
<section class="examples">
119+
120+
## Examples
121+
122+
<!-- eslint no-undef: "error" -->
123+
124+
```javascript
125+
var uniform = require( '@stdlib/random/uniform' );
126+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
127+
var diagonal = require( '@stdlib/ndarray/diagonal' );
128+
129+
// Create a stack of matrices:
130+
var x = uniform( [ 2, 3, 3 ], -10.0, 10.0 );
131+
console.log( ndarray2array( x ) );
132+
133+
// Extract the main diagonals from the stack:
134+
var y = diagonal( x );
135+
console.log( ndarray2array( y ) );
136+
137+
// Extract super-diagonals from the stack:
138+
y = diagonal( x, {
139+
'k': 1
140+
});
141+
console.log( ndarray2array( y ) );
142+
143+
// Extract sub-diagonals from the stack:
144+
y = diagonal( x, {
145+
'k': -1
146+
});
147+
console.log( ndarray2array( y ) );
148+
```
149+
150+
</section>
151+
152+
<!-- /.examples -->
153+
154+
<!-- Section to include cited references. If references are included, add a horizontal rule *before* the section. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
155+
156+
<section class="references">
157+
158+
</section>
159+
160+
<!-- /.references -->
161+
162+
<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->
163+
164+
<section class="related">
165+
166+
</section>
167+
168+
<!-- /.related -->
169+
170+
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
171+
172+
<section class="links">
173+
174+
[@stdlib/ndarray/ctor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/ctor
175+
176+
<!-- <related-links> -->
177+
178+
<!-- </related-links> -->
179+
180+
</section>
181+
182+
<!-- /.links -->
Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
/**
2+
* @license Apache-2.0
3+
*
4+
* Copyright (c) 2026 The Stdlib Authors.
5+
*
6+
* Licensed under the Apache License, Version 2.0 (the "License");
7+
* you may not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing, software
13+
* distributed under the License is distributed on an "AS IS" BASIS,
14+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*/
18+
19+
'use strict';
20+
21+
// MODULES //
22+
23+
var bench = require( '@stdlib/bench' );
24+
var isndarrayLike = require( '@stdlib/assert/is-ndarray-like' );
25+
var empty = require( '@stdlib/ndarray/empty' );
26+
var format = require( '@stdlib/string/format' );
27+
var pkg = require( './../package.json' ).name;
28+
var diagonal = require( './../lib' );
29+
30+
31+
// MAIN //
32+
33+
bench( format( '%s:ndims=2', pkg ), function benchmark( b ) {
34+
var values;
35+
var v;
36+
var i;
37+
38+
/* eslint-disable object-curly-newline, stdlib/line-closing-bracket-spacing */
39+
40+
values = [
41+
empty( [ 2, 2 ], { 'dtype': 'float64' } ),
42+
empty( [ 2, 2 ], { 'dtype': 'float32' } ),
43+
empty( [ 2, 2 ], { 'dtype': 'int32' } ),
44+
empty( [ 2, 2 ], { 'dtype': 'complex128' } ),
45+
empty( [ 2, 2 ], { 'dtype': 'generic' } )
46+
];
47+
48+
/* eslint-enable object-curly-newline, stdlib/line-closing-bracket-spacing */
49+
50+
b.tic();
51+
for ( i = 0; i < b.iterations; i++ ) {
52+
v = diagonal( values[ i%values.length ] );
53+
if ( typeof v !== 'object' ) {
54+
b.fail( 'should return an ndarray' );
55+
}
56+
}
57+
b.toc();
58+
if ( !isndarrayLike( v ) ) {
59+
b.fail( 'should return an ndarray' );
60+
}
61+
b.pass( 'benchmark finished' );
62+
b.end();
63+
});
64+
65+
bench( format( '%s:ndims=3', pkg ), function benchmark( b ) {
66+
var values;
67+
var v;
68+
var i;
69+
70+
/* eslint-disable object-curly-newline, stdlib/line-closing-bracket-spacing */
71+
72+
values = [
73+
empty( [ 2, 2, 2 ], { 'dtype': 'float64' } ),
74+
empty( [ 2, 2, 2 ], { 'dtype': 'float32' } ),
75+
empty( [ 2, 2, 2 ], { 'dtype': 'int32' } ),
76+
empty( [ 2, 2, 2 ], { 'dtype': 'complex128' } ),
77+
empty( [ 2, 2, 2 ], { 'dtype': 'generic' } )
78+
];
79+
80+
/* eslint-enable object-curly-newline, stdlib/line-closing-bracket-spacing */
81+
82+
b.tic();
83+
for ( i = 0; i < b.iterations; i++ ) {
84+
v = diagonal( values[ i%values.length ] );
85+
if ( typeof v !== 'object' ) {
86+
b.fail( 'should return an ndarray' );
87+
}
88+
}
89+
b.toc();
90+
if ( !isndarrayLike( v ) ) {
91+
b.fail( 'should return an ndarray' );
92+
}
93+
b.pass( 'benchmark finished' );
94+
b.end();
95+
});
96+
97+
bench( format( '%s:ndims=3,dims=[0,2]', pkg ), function benchmark( b ) {
98+
var values;
99+
var opts;
100+
var v;
101+
var i;
102+
103+
/* eslint-disable object-curly-newline, stdlib/line-closing-bracket-spacing */
104+
105+
values = [
106+
empty( [ 2, 2, 2 ], { 'dtype': 'float64' } ),
107+
empty( [ 2, 2, 2 ], { 'dtype': 'float32' } ),
108+
empty( [ 2, 2, 2 ], { 'dtype': 'int32' } ),
109+
empty( [ 2, 2, 2 ], { 'dtype': 'complex128' } ),
110+
empty( [ 2, 2, 2 ], { 'dtype': 'generic' } )
111+
];
112+
113+
/* eslint-enable object-curly-newline, stdlib/line-closing-bracket-spacing */
114+
115+
opts = {
116+
'dims': [ 0, 2 ]
117+
};
118+
119+
b.tic();
120+
for ( i = 0; i < b.iterations; i++ ) {
121+
v = diagonal( values[ i%values.length ], opts );
122+
if ( typeof v !== 'object' ) {
123+
b.fail( 'should return an ndarray' );
124+
}
125+
}
126+
b.toc();
127+
if ( !isndarrayLike( v ) ) {
128+
b.fail( 'should return an ndarray' );
129+
}
130+
b.pass( 'benchmark finished' );
131+
b.end();
132+
});
133+
134+
bench( format( '%s:ndims=4', pkg ), function benchmark( b ) {
135+
var values;
136+
var v;
137+
var i;
138+
139+
/* eslint-disable object-curly-newline, stdlib/line-closing-bracket-spacing */
140+
141+
values = [
142+
empty( [ 2, 2, 2, 2 ], { 'dtype': 'float64' } ),
143+
empty( [ 2, 2, 2, 2 ], { 'dtype': 'float32' } ),
144+
empty( [ 2, 2, 2, 2 ], { 'dtype': 'int32' } ),
145+
empty( [ 2, 2, 2, 2 ], { 'dtype': 'complex128' } ),
146+
empty( [ 2, 2, 2, 2 ], { 'dtype': 'generic' } )
147+
];
148+
149+
/* eslint-enable object-curly-newline, stdlib/line-closing-bracket-spacing */
150+
151+
b.tic();
152+
for ( i = 0; i < b.iterations; i++ ) {
153+
v = diagonal( values[ i%values.length ] );
154+
if ( typeof v !== 'object' ) {
155+
b.fail( 'should return an ndarray' );
156+
}
157+
}
158+
b.toc();
159+
if ( !isndarrayLike( v ) ) {
160+
b.fail( 'should return an ndarray' );
161+
}
162+
b.pass( 'benchmark finished' );
163+
b.end();
164+
});
165+
166+
bench( format( '%s:ndims=5', pkg ), function benchmark( b ) {
167+
var values;
168+
var v;
169+
var i;
170+
171+
/* eslint-disable object-curly-newline, stdlib/line-closing-bracket-spacing */
172+
173+
values = [
174+
empty( [ 2, 2, 2, 2, 2 ], { 'dtype': 'float64' } ),
175+
empty( [ 2, 2, 2, 2, 2 ], { 'dtype': 'float32' } ),
176+
empty( [ 2, 2, 2, 2, 2 ], { 'dtype': 'int32' } ),
177+
empty( [ 2, 2, 2, 2, 2 ], { 'dtype': 'complex128' } ),
178+
empty( [ 2, 2, 2, 2, 2 ], { 'dtype': 'generic' } )
179+
];
180+
181+
/* eslint-enable object-curly-newline, stdlib/line-closing-bracket-spacing */
182+
183+
b.tic();
184+
for ( i = 0; i < b.iterations; i++ ) {
185+
v = diagonal( values[ i%values.length ] );
186+
if ( typeof v !== 'object' ) {
187+
b.fail( 'should return an ndarray' );
188+
}
189+
}
190+
b.toc();
191+
if ( !isndarrayLike( v ) ) {
192+
b.fail( 'should return an ndarray' );
193+
}
194+
b.pass( 'benchmark finished' );
195+
b.end();
196+
});

0 commit comments

Comments
 (0)