matlab - Straighten and concatenate the individual grids from ndgrid -
this question has answer here:
i'm trying following in general way:
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
i believe have start following way, can't figure out how continue:
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
i can solve in many ways case 3 variables [a, b, c]
, both , without loops, start struggle when more vectors. reshaping directly not give correct result, , mixing reshape permute becomes hard when have arbitrary number of dimensions.
can think of clever way scales 3-30 vectors in x
?
you can use cellfun
flatten each of cell array elements , concatenate them along second dimension.
tmp = cellfun(@(x)x(:), cell_grid, 'uniformoutput', false); out = cat(2, tmp{:})
alternately, avoid cellfun
, concatenate them along dimension 1 higher dimension of each cell_grid
member (i.e. numel(x) + 1
). reshape
flatten dimensions last 1 concatenated along.
out = reshape(cat(numel(x) + 1, cell_grid{:}), [], numel(x));
Comments
Post a Comment