Skip to content

Commit c1fd52a

Browse files
committed
feat: add ndarray/diagonal
1 parent acd2375 commit c1fd52a

10 files changed

Lines changed: 1451 additions & 0 deletions

File tree

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
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 class="intro">
26+
27+
For an `M`-by-`N` matrix `A`, the `k`-th diagonal is defined as
28+
29+
<!-- <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."> -->
30+
31+
```math
32+
D_k = \{\, A_{i,j} : j - i = k \,\}
33+
```
34+
35+
<!-- <div class="equation" align="center" data-raw-text="D_k = \{\, A_{i,j} : j - i = k \,\}" data-equation="eq:diagonal_definition">
36+
<img src="" alt="Definition of the k-th diagonal of a matrix.">
37+
<br>
38+
</div> -->
39+
40+
<!-- </equation> -->
41+
42+
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).
43+
44+
</section>
45+
46+
<!-- /.intro -->
47+
48+
<section class="usage">
49+
50+
## Usage
51+
52+
```javascript
53+
var diagonal = require( '@stdlib/ndarray/diagonal' );
54+
```
55+
56+
#### diagonal( x\[, options] )
57+
58+
Returns a read-only view of the diagonal of a matrix (or stack of matrices) `x`.
59+
60+
```javascript
61+
var array = require( '@stdlib/ndarray/array' );
62+
63+
var x = array( [ [ 1.0, 2.0, 3.0 ], [ 4.0, 5.0, 6.0 ], [ 7.0, 8.0, 9.0 ] ] );
64+
// returns <ndarray>[ [ 1.0, 2.0, 3.0 ], [ 4.0, 5.0, 6.0 ], [ 7.0, 8.0, 9.0 ] ]
65+
66+
var y = diagonal( x );
67+
// returns <ndarray>[ 1.0, 5.0, 9.0 ]
68+
```
69+
70+
The function accepts the following arguments:
71+
72+
- **x**: input [`ndarray`][@stdlib/ndarray/ctor].
73+
- **options**: function options.
74+
75+
The function accepts the following options:
76+
77+
- **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`.
78+
- **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]`.
79+
80+
</section>
81+
82+
<!-- /.usage -->
83+
84+
<section class="notes">
85+
86+
## Notes
87+
88+
- 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.
89+
- Each provided dimension index must reside on the interval `[-ndims, ndims-1]`.
90+
91+
</section>
92+
93+
<!-- /.notes -->
94+
95+
<section class="examples">
96+
97+
## Examples
98+
99+
<!-- eslint no-undef: "error" -->
100+
101+
```javascript
102+
var uniform = require( '@stdlib/random/uniform' );
103+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
104+
var diagonal = require( '@stdlib/ndarray/diagonal' );
105+
106+
// Create a stack of matrices:
107+
var x = uniform( [ 2, 3, 3 ], -10.0, 10.0 );
108+
console.log( ndarray2array( x ) );
109+
110+
// Extract the main diagonals from the stack:
111+
var y = diagonal( x );
112+
console.log( ndarray2array( y ) );
113+
114+
// Extract super-diagonals from the stack:
115+
y = diagonal( x, {
116+
'k': 1
117+
});
118+
console.log( ndarray2array( y ) );
119+
120+
// Extract sub-diagonals from the stack:
121+
y = diagonal( x, {
122+
'k': -1
123+
});
124+
console.log( ndarray2array( y ) );
125+
```
126+
127+
</section>
128+
129+
<!-- /.examples -->
130+
131+
<section class="references">
132+
133+
</section>
134+
135+
<!-- /.references -->
136+
137+
<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->
138+
139+
<section class="related">
140+
141+
</section>
142+
143+
<!-- /.related -->
144+
145+
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
146+
147+
<section class="links">
148+
149+
[@stdlib/ndarray/ctor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/ctor
150+
151+
<!-- <related-links> -->
152+
153+
<!-- </related-links> -->
154+
155+
</section>
156+
157+
<!-- /.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)