Cartesian product in MATLAB

emper picture emper · Mar 23, 2012 · Viewed 21.7k times · Source

Here is the simplified version of the problem I have. Suppose I have a vector

p=[1 5 10]

and another one

q=[.75 .85 .95].

And I want to come up with the following matrix:

res=[1, .75;1, .85; 1, .95; 5, .75; 5, .85; 5, .95; 10, .75; 10, .85; 10, .95].

This is also known as the Cartesian Product. How can I do that?

Many thanks

Answer

nibot picture nibot · Mar 23, 2012

Here's one way:

[X,Y] = meshgrid(p,q);
result = [X(:) Y(:)];

The output is:

result =

    1.0000    0.7500
    1.0000    0.8500
    1.0000    0.9500
    5.0000    0.7500
    5.0000    0.8500
    5.0000    0.9500
   10.0000    0.7500
   10.0000    0.8500
   10.0000    0.9500