reshape

Returns a new slice for the same data with different dimensions.

@optmath
Slice!(Iterator, M, kind)
reshape
(
Iterator
size_t N
SliceKind kind
size_t M
)
(
Slice!(Iterator, N, kind) slice
,
ptrdiff_t[M] rlengths
,
ref int err
)

Parameters

slice Slice!(Iterator, N, kind)

slice to be reshaped

rlengths ptrdiff_t[M]

list of new dimensions. One of the lengths can be set to -1. In this case, the corresponding dimension is inferable.

err int

Return Value

Type: Slice!(Iterator, M, kind)

reshaped slice

Examples

import mir.ndslice.dynamic : allReversed;
int err;
auto slice = iota(3, 4)
    .universal
    .allReversed
    .reshape([-1, 3], err);
assert(err == 0);
assert(slice ==
    [[11, 10, 9],
     [ 8,  7, 6],
     [ 5,  4, 3],
     [ 2,  1, 0]]);

Reshaping with memory allocation

import mir.ndslice.slice: sliced;
import mir.ndslice.allocation: slice;
import mir.ndslice.dynamic : reversed;

auto reshape2(S, size_t M)(S sl, ptrdiff_t[M] lengths)
{
    int err;
    // Tries to reshape without allocation
    auto ret = sl.reshape(lengths, err);
    if (!err)
        return ret;
    if (err == ReshapeError.incompatible)
        // allocates, flattens, reshapes with `sliced`, converts to universal kind
        return sl.slice.flattened.sliced(cast(size_t[M])lengths).universal;
    throw new Exception("total elements count is different or equals to zero");
}

auto sl = iota!int(3, 4)
    .slice
    .universal
    .reversed!0;

assert(reshape2(sl, [4, 3]) ==
    [[ 8, 9, 10],
     [11, 4,  5],
     [ 6, 7,  0],
     [ 1, 2,  3]]);

Meta