The OpenD Programming Language

diagonal

Returns a 1-dimensional slice over the main diagonal of an n-dimensional slice. diagonal can be generalized with other selectors such as blocks (diagonal blocks) and windows (multi-diagonal slice).

Slice!(Iterator, 1, N == 1 ? kind : Universal)
diagonal
(
Iterator
size_t N
SliceKind kind
)
(
Slice!(Iterator, N, kind) slice
)

Parameters

slice Slice!(Iterator, N, kind)

input slice

Return Value

Type: Slice!(Iterator, 1, N == 1 ? kind : Universal)

1-dimensional slice composed of diagonal elements

Examples

Matrix, main diagonal

//  -------
// | 0 1 2 |
// | 3 4 5 |
//  -------
//->
// | 0 4 |
static immutable d = [0, 4];
assert(iota(2, 3).diagonal == d);

Non-square matrix

//  -------
// | 0 1 |
// | 2 3 |
// | 4 5 |
//  -------
//->
// | 0 3 |

assert(iota(3, 2).diagonal == iota([2], 0, 3));

Loop through diagonal

import mir.ndslice.slice;
import mir.ndslice.allocation;

auto slice = slice!int(3, 3);
int i;
foreach (ref e; slice.diagonal)
    e = ++i;
assert(slice == [
    [1, 0, 0],
    [0, 2, 0],
    [0, 0, 3]]);

Matrix, subdiagonal

//  -------
// | 0 1 2 |
// | 3 4 5 |
//  -------
//->
// | 1 5 |
static immutable d = [1, 5];
auto a = iota(2, 3).canonical;
a.popFront!1;
assert(a.diagonal == d);

3D, main diagonal

//  -----------
// |  0   1  2 |
// |  3   4  5 |
//  - - - - - -
// |  6   7  8 |
// |  9  10 11 |
//  -----------
//->
// | 0 10 |
static immutable d = [0, 10];
assert(iota(2, 2, 3).diagonal == d);

3D, subdiagonal

//  -----------
// |  0   1  2 |
// |  3   4  5 |
//  - - - - - -
// |  6   7  8 |
// |  9  10 11 |
//  -----------
//->
// | 1 11 |
static immutable d = [1, 11];
auto a = iota(2, 2, 3).canonical;
a.popFront!2;
assert(a.diagonal == d);

3D, diagonal plain

//  -----------
// |  0   1  2 |
// |  3   4  5 |
// |  6   7  8 |
//  - - - - - -
// |  9  10 11 |
// | 12  13 14 |
// | 15  16 17 |
//  - - - - - -
// | 18  20 21 |
// | 22  23 24 |
// | 24  25 26 |
//  -----------
//->
//  -----------
// |  0   4  8 |
// |  9  13 17 |
// | 18  23 26 |
//  -----------

static immutable d =
    [[ 0,  4,  8],
     [ 9, 13, 17],
     [18, 22, 26]];

auto slice = iota(3, 3, 3)
    .pack!2
    .evertPack
    .diagonal
    .evertPack;

assert(slice == d);

See Also

Meta