2

I'm new to matlab and have a question on how to efficiently create a matrix from two or more vectors, where every combination of a single element from each vector is represented in a resulting matrix.

For example, say we have vectors:

x = [1 2 3 4];  y = [5 6 7 8];

I'd like to get the following result in matrix ans:

ans = [1 5; 1 6; 1 7; 1 8; 2 5; 2 6; 2 7; ... 4 7; 4 8]

The above example is for two-dimensions (two input vectors), however it would be ideal if the solution is for d-dimensions (d-number of input vectors). Thanks!

2 Answers2

0
[X,Y] = ndgrid(x,y);
desiredOutput = [X(:),Y(:)];
Alex Taylor
  • 1,402
  • 1
  • 9
  • 15
0

Here is the solution for d dimensions.

%% Input.
x = [1 2 3 4];
y = [5 6 7 8];


%% Fixed 2d solution as provided by Alex.
[X, Y] = ndgrid(x, y);
desiredOutput = [X(:), Y(:)]


%% Arbitrary dimension solution.

% Store all input vectors in cell array.
vectors{1} = x;
vectors{2} = y;

% Initialize output for ndgrid.
VECTORS = cell(numel(vectors), 1);

% Call ndgrid with arbitrary number of vectors.
[VECTORS{:}] = ndgrid(vectors{:});

% Convert VECTORS.
VECTORS = cellfun(@(x) x(:), VECTORS, 'UniformOutput', false);

% Output.
desiredOutput = [VECTORS{:}]


%% Expanded input.
z = [9 10 11 12];
vectors{3} = z;
VECTORS = cell(numel(vectors), 1);[VECTORS{:}] = ndgrid(vectors{:});
VECTORS = cellfun(@(x) x(:), VECTORS, 'UniformOutput', false);
desiredOutput = [VECTORS{:}]
HansHirse
  • 18,010
  • 10
  • 38
  • 67