Search code examples
arraysmatlabcell-array

Convert output of ndgrid to a single array


I want to create an n-dimensional grid from vectors xi which specify the desired grid points in dimension i. The output should be a single N x n matrix, where N=b1*b2*b3*...*bn is the total number of grid points, and bi is the number of desired grid points along that dimension. (I want to do this in Matlab.)

I know that I can use the ndgrid function to create this n-dimensional grid, but ndgrid returns n cell arrays, each of dimension b1xb2xb3x...xbn. How can I transform this to a single array, as desired?

An additional complication: I do not know the dimension n in advance.


Solution

  • David already got the idea in his comment, just a minor error for n>=4.

    function grid_array = ndgridarr(n, varargin)
    
        assert(length(varargin) == 1 || length(varargin) == n);
    
        grid_cells = cell(1, n);
        [grid_cells{:}] = ndgrid(varargin{:});
    
        grid_array = reshape(cat(n+1,grid_cells{:}),[],n);
    end
    

    An alternative is to use allcomb from file exchange or combvec (Deep learning toolbox). They both already return a single matrix, no need to stich the cell array together.