user42459
user42459

Reputation: 915

N-dimensional MatLab Meshgrid

I know I can do this by meshgrid up to 3-dimensional space.

If I do

[X,Y] = meshgrid(1:3,10:14,4:8)

as in http://www.mathworks.com/help/matlab/ref/meshgrid.html, then I will get the grid points on the 3-D space.

But meshgrid can't do this for n-dimensional space.

How should I get grid points (do similar thing like meshgrid) on n-dimensional space (e.g. n=64) ?

Upvotes: 1

Views: 1026

Answers (1)

Suever
Suever

Reputation: 65430

To create a grid of n-dimensional data, you will want to use ndgrid

[yy,xx,zz,vv] = ndgrid(yrange, xrange, zrange, vrange);

This can be expanded to any arbitrary number of dimensions.

As Daniel notes, notice that the first two outputs are reversed in their naming since y (rows) are the first dimension in MATLAB.

If you want to go to really high dimensions (such as 64), when the inputs/outputs get unmanageable, you can setup cell arrays for the inputs and outputs and rely on cell array expansion to do the work:

ranges = cell(64, 1);
ranges{1} = xrange;
ranges{2} = yrange;
...
ranges{64} = vals;

outputs = cell(size(ranges);
[outputs{:}] = ndgrid(ranges{:});

As a side note, this can really blow up quickly as your number of dimensions grows. There may be a more elegant solution to what you're ultimately trying to do.

For example if I create example inputs (at 64 dimensions) and for each dimension choose a random number between 1 and 5 for the length, I get a "maximum variable size" error

ranges = arrayfun(@(x)1:randi([1 5]), 1:64, 'uniform', 0);
[xx,yy] = ndgrid(ranges{:});

Upvotes: 5

Related Questions