blocks

Returns an n-dimensional slice of n-dimensional non-overlapping blocks. blocks can be generalized with other selectors. For example, blocks in combination with diagonal can be used to get a slice of diagonal blocks. For overlapped blocks, combine windows with strided.

@optmath
Slice!(SliceIterator!(Iterator, N, N == 1 ? Universal : min(kind, Canonical)), N, Universal)
blocks
(
Iterator
size_t N
SliceKind kind
)
(
Slice!(Iterator, N, kind) slice
,
size_t[N] rlengths_...
)

Parameters

N

dimension count

slice Slice!(Iterator, N, kind)

slice to be split into blocks

rlengths_ size_t[N]

dimensions of block, residual blocks are ignored

Return Value

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

packed N-dimensional slice composed of N-dimensional slices

Examples

import mir.ndslice.slice;
import mir.ndslice.allocation;
auto slice = slice!int(5, 8);
auto blocks = slice.blocks(2, 3);
int i;
foreach (blocksRaw; blocks)
    foreach (block; blocksRaw)
        block[] = ++i;

assert(blocks ==
    [[[[1, 1, 1], [1, 1, 1]],
      [[2, 2, 2], [2, 2, 2]]],
     [[[3, 3, 3], [3, 3, 3]],
      [[4, 4, 4], [4, 4, 4]]]]);

assert(    slice ==
    [[1, 1, 1,  2, 2, 2,  0, 0],
     [1, 1, 1,  2, 2, 2,  0, 0],

     [3, 3, 3,  4, 4, 4,  0, 0],
     [3, 3, 3,  4, 4, 4,  0, 0],

     [0, 0, 0,  0, 0, 0,  0, 0]]);

Diagonal blocks

import mir.ndslice.slice;
import mir.ndslice.allocation;
auto slice = slice!int(5, 8);
auto blocks = slice.blocks(2, 3);
auto diagonalBlocks = blocks.diagonal.unpack;

diagonalBlocks[0][] = 1;
diagonalBlocks[1][] = 2;

assert(diagonalBlocks ==
    [[[1, 1, 1], [1, 1, 1]],
     [[2, 2, 2], [2, 2, 2]]]);

assert(blocks ==
    [[[[1, 1, 1], [1, 1, 1]],
      [[0, 0, 0], [0, 0, 0]]],
     [[[0, 0, 0], [0, 0, 0]],
      [[2, 2, 2], [2, 2, 2]]]]);

assert(slice ==
    [[1, 1, 1,  0, 0, 0,  0, 0],
     [1, 1, 1,  0, 0, 0,  0, 0],

     [0, 0, 0,  2, 2, 2,  0, 0],
     [0, 0, 0,  2, 2, 2,  0, 0],

     [0, 0, 0, 0, 0, 0, 0, 0]]);

Matrix divided into vertical blocks

import mir.ndslice.allocation;
import mir.ndslice.slice;
auto slice = slice!int(5, 13);
auto blocks = slice
    .pack!1
    .evertPack
    .blocks(3)
    .unpack;

int i;
foreach (block; blocks)
    block[] = ++i;

assert(slice ==
    [[1, 1, 1,  2, 2, 2,  3, 3, 3,  4, 4, 4,  0],
     [1, 1, 1,  2, 2, 2,  3, 3, 3,  4, 4, 4,  0],
     [1, 1, 1,  2, 2, 2,  3, 3, 3,  4, 4, 4,  0],
     [1, 1, 1,  2, 2, 2,  3, 3, 3,  4, 4, 4,  0],
     [1, 1, 1,  2, 2, 2,  3, 3, 3,  4, 4, 4,  0]]);

See Also

Meta