Skip to content

← Tensor Foundations step 7 of 7

Easy Framework

Concatenate Tensors

Concatenation joins tensors along an existing axis. Here, both inputs and the result are matrices: no new axis is added.

Your task

Implement concat(a, b, axis) for two-dimensional tensors with the same dtype and device. The supplied axis is either 0 or 1, and the other dimension matches. Return the joined tensor, preserving dtype and device. Leave both inputs unchanged.

  • With axis=0, append b's rows after a's rows. Shapes (m, n) and (k, n) produce (m + k, n).
  • With axis=1, append b's columns after a's columns in each row. Shapes (m, n) and (m, k) produce (m, n + k).

For a=[[1, 2]] and b=[[3, 4]], axis=0 gives [[1, 2], [3, 4]], while axis=1 gives [[1, 2, 3, 4]].

The inputs need not have identical shapes. For example, joining [[1], [2]] and [[3, 4], [5, 6]] along axis 1 gives [[1, 3, 4], [2, 5, 6]]: only the row counts need to match.

Use torch.cat([a, b], dim=axis) or jnp.concatenate([a, b], axis=axis). Keep a before b along the chosen axis. Do not flatten the inputs or use stack, which would introduce a new dimension.