ndgrid on cell array of vectors

4 views (last 30 days)
jack
jack on 1 Dec 2015
Commented: jack on 2 Dec 2015
hi guys,
i need your help in solving the following question:
Given a cell array of vectors where each index represent a range of elements in dimension i, how can you apply ndgrid of the vectors?
To ease the question, here is an example:
Thanks in advance.

Accepted Answer

Guillaume
Guillaume on 1 Dec 2015
What you are asking for is the cartesian product of the sets.
If your cell array only contains two sets (each with arbitrary size):
c1 = {{[1 2],[2 3]}, {[10 11], [11 12]}}
assert(numel(c1) == 2, 'only works with two sets')
[idx1, idx2] = ndgrid(1:numel(c1{1}), 1:numel(c1{2});
c2 = arrayfun(@(i1, i2) [c1{1}(i1), c1{2}(i2)], idx1(:), idx2(:), 'UniformOutput', false);
c2 = vertcat(c2{:})
A completely generic version that works with any number of sets:
c1 = {{[1 2],[2 3]}, {[10 11], [11 12]}, {4, 5, [6 7]}} %3 sets here
indices = cell(1, numel(c1)); %output variable for ndgrid
ndgridin = cellfun(@(c) 1:numel(c), c1, 'UniformOutput', false); %input arrays for ndgrid
[indices{:}] = ndgrid(ndgridin{:}); %get ngrid result
indices = cellfun(@(idx) reshape(idx, [], 1), indices, 'UniformOutput', false); %reshape ndgrid outputs into columns
catfun = @(nset, subsets) [arrayfun(@(n, i) c1{n}{i}, nset, subsets, 'UniformOutput', false)];
c2 = arrayfun(@(varargin) catfun(1:numel(c1), [varargin{:}]), indices{:}, 'UniformOutput', false);
c2 = vertcat(c2{:})

More Answers (1)

Walter Roberson
Walter Roberson on 1 Dec 2015
ndgrid indices and use the indices to index the cell array.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!