Search code examples
matlabmatrixdimension

Matlab: Can I create a matrix with unknown number of dimensions?


Normally a matrix has 2 dimensions, but there doesn't seem to be a limit on the number of dimensions a matrix may have in MATLAB.

To create a 4-dimensional matrix, for example, I can do this:

>> x = zeros(2,2,2,2)

x(:,:,1,1) =

     0     0
     0     0


x(:,:,2,1) =

     0     0
     0     0


x(:,:,1,2) =

     0     0
     0     0


x(:,:,2,2) =

     0     0
     0     0

Is there a way to create a matrix of which the number of dimensions is only known at runtime?


Solution

  • You could call zeros like this:

    x = zeros([2 2 2 2])
    

    Hence, you can customize the input array as you want.

    For example: to create a 2x2x2x2x2 matrix (where D = 5, the number of dimensions):

    D = 5;
    x = zeros(zeros(1, D) + 2)