Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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 it isn't very elegant.

share|improve this question

migrated from stackoverflow.com Feb 4 '13 at 3:47

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

1 Answer 1

up vote 3 down vote accepted

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
share|improve this answer
    
Great, thanks Thierry. –  Sean Connolly Feb 1 '13 at 18:46

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.