1

For example, ndgrid has inputs as n vectors where n is decided by the user.

For my use case, n can change. I would like to prepare the input list before hand, based on n, then feed the inputs to ndgrid. How do I do that please?

For example, say I have 3 row vectors x1, x2, and x3. Then, if n=3 and I put inputs = [x1,x2,x3], and I use ndgrid(inputs) then MATLAB treats this as ndgrid([x1,x2,x3]) instead of ndgrid(x1,x2,x3). I want the latter, not the former. How do I solve this please?

yurnero
  • 315
  • 2
  • 9
  • See https://stackoverflow.com/questions/8598085/split-a-list-into-several-variables-in-matlab. 'deal' function may helps – zlon Jan 21 '21 at 07:14

1 Answers1

3

When we use a cell array, for example x = {some,stuff,inside} you can unpack the cell with x{:}, in a function call, each elements of the cell will be passed as an argument: myfunction(x{:}) is equivalent to myfunction(some, stuff, inside).

In your case:

% Number of inputs
k = 3;
% Put your k input in a cell array
x = {1:3,1:3,1:3};
% If needed you can also have a dynamic output variable
X = cell(k,1);
% Get the result
[X{:}] = ndgrid(x{:})
obchardon
  • 10,614
  • 1
  • 17
  • 33