HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Build a combinatorial matrix from two vectors

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
vectorscombinatorialtwofrommatrixbuild

Problem

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.

Solution

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

Code Snippets

y = [10 30 50 70]

x = [10 30 50]

[X,Y] = meshgrid(y,x);
result = [Y(:) X(:)];
10   10
30   10
50   10
10   30
30   30
50   30
10   50
30   50
50   50
10   70
30   70
50   70

Context

StackExchange Code Review Q#21272, answer score: 3

Revisions (0)

No revisions yet.