# Matlab - build a combinatorial matrix from two vectors

I want to define a matrix of values with a very simple pattern. I've achieved it with the code below but it's ugly - very difficult to read (I find) and surely not as optimal, in terms of performance, as it could be. The former is really what I'm trying to address here. I feel this can be done much more elegantly and would love some guidance from the community.

Here is an example of what I am hoping to achieve, from x and y I want to get points..

y =

10    30    50    70

x =

10    30    50

points =

10    10
30    10
50    10
10    30
30    30
50    30
10    50
30    50
50    50
10    70
30    70
50    70


x and y are, of course, no always those exact vectors. They are, however, very simply created. Something like so..

scale = 20;
max_x = 85;
max_y = 62;

y_count = floor(max_x / scale);
x_count = floor(max_y / scale);

y = ((1:y_count) * scale) - scale / 2;
x = ((1:x_count) * scale) - scale / 2;


Here's my brute force approach..

y = repmat(y, x_count, 1);
y = reshape(y, 1, size(y, 1) * size(y, 2));
y = y';

x = repmat(x, y_count, 1);
x = x';
x = reshape(x, 1, size(x, 1) * size(x, 2));
x = x';

points = [x y];


It works.. but isn't very elegant.

PS: correct me if there's a better title for this question.

-

## migrated from stackoverflow.comFeb 4 '13 at 3:47

This question came from our site for professional and enthusiast programmers.

It's called Cartesian product and you can do that easily:

Here's one way:

y = [10 30 50 70]

x = [10 30 50]

[X,Y] = meshgrid(y,x);
result = [Y(:) X(:)];


Result:

10   10
30   10
50   10
10   30
30   30
50   30
10   50
30   50
50   50
10   70
30   70
50   70

-
Great, thanks Thierry. –  Sean Connolly Feb 1 '13 at 18:46