# Concatenate two images in the channel dimension?

I have to concatenate two images in the channel dimension in either MATLAB or Python.

Let's say we take two gray-scale input images, where each has for example the dimension `[1, 1, 28, 28]` (i.e. 1 image, 1 channel, 28x28 resolution). How can we concatenate them to be one image of size `[1, 2, 28, 28]`?

I'm not sure what you want to do with your fist dimension but this works for your example:

``````img1 = randi(255,1,1,28,28); % first image
img2 = randi(255,1,1,28,28); % second image

img1(1,end+1,:,:) = img2; % stack second image on top of first image
size(img1) % [ 1 2 28 28]
``````

In MATLAB you would usually use the `cat` command for this:

``````bigMat = cat(dimNo, matA, matB); % dimNo can be 1, 2, ...
``````

But in the case of concatenating along the 2nd dimension, you can also simply use `[... ; ...]`:

``````bigMat = [matA; matB];
``````

(which is equivalent to the `vertcat` function).

If you know in advance how many matrices you'd like to concatenate (i.e. the final size of the result), you should preallocate your matrix using e.g. `bigMat = zeros(1, N, 28, 28)`, then put each image in its correct position similarly to the previous answer -

``````img1(:,n,:,:) = img2; % where n is 1..N, and not anything like end+1
``````

We don't want to use `end+1` as this incurs performance losses related to constant reallocation of larger and larger arrays and copying all contents of the array each time.

``````import numpy as np
The argument `axis=1` defines the axis along which the operation is executed.