Straighten and concatenate the individual grids from ndgrid <p>I'm trying to do the following in a general way:</p> <pre><code>x = {0:1, 2:3, 4:6}; [a,b,c] = ndgrid(x{:}); Res = [a(:), b(:), c(:)] Res = 0 2 4 1 2 4 0 3 4 1 3 4 0 2 5 1 2 5 0 3 5 1 3 5 0 2 6 1 2 6 0 3 6 1 3 6 </code></pre> <p>I believe I have to start the following way, but I can't figure out how to continue:</p> <pre><code>cell_grid = cell(1,numel(x)); [cell_grid{:}] = ndgrid(x{:}); [cell_grid{:}] ans = ans(:,:,1) = 0 0 2 3 4 4 1 1 2 3 4 4 ans(:,:,2) = 0 0 2 3 5 5 1 1 2 3 5 5 ans(:,:,3) = 0 0 2 3 6 6 1 1 2 3 6 6 </code></pre> <p>I can solve this in many ways for the case with three variables <code>[a, b, c]</code>, both with and without loops, but I start to struggle when I get more vectors. Reshaping it directly will not give the correct result, and mixing reshape with permute becomes really hard when I have arbitrary number of dimensions.</p> <p>Can you think of a clever way to do this that scales to 3-30 vectors in <code>x</code>?</p>