GitHub
deepbox/ndarray

Shape & Indexing

Operations for reshaping, transposing, slicing, and indexing tensors. These are zero-copy when possible (strided views).
reshape
reshape(t: Tensor, shape: Shape): Tensor

Change tensor shape without copying data when possible. The total number of elements must remain the same. Use -1 for one inferred dimension.

Parameters:
shape: Shape - Target shape (e.g., [2, 6] or [3, -1])
transpose
transpose(t: Tensor, axes?: number[]): Tensor

Permute tensor dimensions. Without axes argument, reverses all dimensions (matrix transpose). Creates a strided view — no data copy.

Parameters:
axes: number[] - New order of dimensions. Default: reversed.
flatten
flatten(t: Tensor): Tensor

Collapse all dimensions into a single 1D tensor. Equivalent to reshape(t, [-1]).

squeeze
squeeze(t: Tensor, axis?: number): Tensor

Remove size-1 dimensions. If axis is specified, only removes that dimension (must be size 1).

unsqueeze
unsqueeze(t: Tensor, axis: number): Tensor

Insert a size-1 dimension at the specified position. Useful for broadcasting.

expandDims
expandDims(t: Tensor, axis: number): Tensor

Alias for unsqueeze. Adds a new axis at the given position.

slice
slice(t: Tensor, ranges: SliceRange[]): Tensor

Extract a sub-tensor using [start, stop] ranges for each dimension. Returns a strided view — no data copy.

Parameters:
ranges: SliceRange[] - Array of [start, stop] pairs, one per dimension
gather
gather(t: Tensor, indices: Tensor, axis: number): Tensor

Gather elements along an axis using an index tensor. Supports autograd backward pass.

shape-indexing.ts
import { tensor, reshape, transpose, flatten, squeeze, unsqueeze, slice, gather } from "deepbox/ndarray";const t = tensor([[1, 2, 3], [4, 5, 6]]);// Reshapereshape(t, [3, 2]);   // [[1, 2], [3, 4], [5, 6]]reshape(t, [6]);      // [1, 2, 3, 4, 5, 6]reshape(t, [-1]);     // [1, 2, 3, 4, 5, 6] (-1 inferred)// Transposetranspose(t);         // [[1, 4], [2, 5], [3, 6]]// Flattenflatten(t);           // [1, 2, 3, 4, 5, 6]// Squeeze/Unsqueezeconst s = tensor([[[1, 2, 3]]]); // shape: [1, 1, 3]squeeze(s);           // shape: [3]unsqueeze(t, 0);      // shape: [1, 2, 3]// Slicingslice(t, [[0, 1], [1, 3]]); // [[2, 3]] (row 0, cols 1-2)// Gatherconst idx = tensor([0, 2], { dtype: "int32" });gather(t, idx, 1);    // [[1, 3], [4, 6]]

When to Use

  • reshape — Match expected input shapes for layers (e.g., flatten before Linear)
  • transpose — Convert between row-major and column-major, or permute batch dimensions
  • squeeze/unsqueeze — Add or remove batch dimensions for broadcasting
  • slice — Extract windows, crops, or sub-sequences from tensors
  • gather — Implement embedding lookups, advanced indexing, or attention patterns