4
\$\begingroup\$

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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Feb 1, 2013 at 14:20
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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
answered Feb 1, 2013 at 14:43
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.