Search code examples
matlabmultidimensional-array

How to allocate an array with a size defined by two vectors?


I want to create zeros of size defined by two vectors, which will work in 2D and 3D.

%% Setting in 2D
% rectangular domain with left bottom corner [_1,_2]
% and right top  corner [_1,_2]

    lb_corner=[-1,-2]
    rt_corner=[2,2]

    domain_size=rt_corner - lb_corner; 

    dim=size(domain_size,2);

    nb_pixels=[5,4]; % number of pixels in [x_1,x_2]

%% Mesh parameters
   pixel_size= domain_size./nb_pixels;

%% Coordinates

    if dim == 2
        x_coords=zeros(nb_pixels(1),nb_pixels(2),dim);
    elseif dim == 3
        x_coords=zeros(nb_pixels(1),nb_pixels(2),nb_pixels(3),dim);

    end

In three dimensions the vectors would look like this:,

%% Setting in 3D
lb_corner = [-2,-2,-2]
rt_corner = [2,2,2] 
domain_size=rt_corner - lb_corner; 

dim=size(domain_size,2); 
nb_pixels=[5,4,5]; % number of pixels in [x_1,x_2,x_3] 

I want to replace if condition with something like:

%    x_coords=zeros(nb_pixels,dim); 

this should create array of size (nb_pixels(1),nb_pixels(2),dim) in 2D, and array of size (nb_pixels(1),nb_pixels(2),nb_pixels(3),dim) in 3D


Solution

  • You can just concatenate them and hand zeros the size array:

    x_coords=zeros([nb_pixels,dim]);