Consider an array with $t=10000$ rows, $i=2$ columns and $n=41$ as a 3rd dimension. Now I add the columns of this array to yield a matrix with $t$ rows and $n$ columns. However in MATLAB the size of my new matrix X is:

size(X) = 10000   1   41

I want to add $10000$ zeros to each of the columns of this matrix. This should give a matrix with:

size(X) = 20000   1   41

I would try this code:

X_zeros = [X;zeros(10000,41)];

However, apparently the dimensions of X and zeros(10000,41) are not matching. I assume it is because of my 3rd dimension, although this 3rd dimension is empty. I want to delete this 3rd dimension s.t. :

size(X_zeros) = 20000   41

This is not an option:

X_zeros = [X,zeros(10000,1,41)]

because I assign X_zeros to other matrices with only $2$ dimensions. Is there a way?


When you sum a three dimensional array over the third dimension, the size is automatically reduced by one:

a = rand(2,3,4); % a random 3-d array
b = sum(a,3);    % sum over the third dimension: the size of b becomes 2 by 3

So the first solution to this is to form the original array with size $10000\times41\times2$ from the beginning (if it is not difficult).

If it is not straightforward, there are two options.

  • You may find tricks to actually do what you want to do in 3D. However, in this way your 2D data is unnecessarily 3D which makes everything cumbersome and slows the calculations. So this option is not recommended.

  • Alternatively, you can reshape the 3d matrix to a 2d matrix and fix the problem at its root:

    a = rand(2,3,4); % a random 3-d array
    b = sum(a,2);    % sum over the second dimension: the size of b becomes 2 by 1 by 3
    b = reshape(b,size(b,1),size(b,3)); the size of b becomes 2 by 3

Now let's get back to your $10000\times41$ matrix. I am not sure if you want to add $10000$ zeros to each row of this matrix or to the columns (it is not clear). what you did (X_zeros = [X;zeros(10000,41)];), actually pads a zero matrix of size $10000\times41$ at the bottom of X. If that is actually what you are looking for, here is the code:

a = rand(10000,2,41);
b = sum(a,2);
b = reshape(b,size(b,1),size(b,3));
c = cat(1,b,zeros(size(b)));

A lovely cat ("concatenate arrays along specific dimension") can do the job:

a = randn(10000,1,41);b= cat(1,a,zeros(size(a)));whos b

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy