mohamed
mohamed

Reputation: 29

Generating all points of grid from given vectors of vertical and horizontal coordinates - MATLAB

I have a square grid of 10 by 10 points. v1 is the vector of horizontal coordinates and v2 is the vector that contains the vertical coordinates. From these two vectors, I want to construct all the 100 points. Here is a 2 by 2 example:

v1 = [1 2];
v2 = [3 4];

Then the 4 points I want to generate are:

p(1,:) = [1,3]
p(2,:) = [1,4]
p(3,:) = [2,3]
p(4,:) = [2,4]

How can this be done in MATLAB?

Upvotes: 0

Views: 698

Answers (2)

Benoit_11
Benoit_11

Reputation: 13945

If you have the Neural Network Toolbox you are looking for the combvec function, which creates all combinations from 2 vectors.

Example:

v1=[1 2] 

v2=[3 4]

V = combvec(v1,v2)

which outputs:

V =

     1     2     1     2
     3     3     4     4

Upvotes: 1

knedlsepp
knedlsepp

Reputation: 6084

You will want to use meshgrid or even better: ndgrid. The concept of both functions is the same, but ndgrid is more general and has a sorting of the output that is often more useful.

x = [1,2];
y = [3,4];
[X, Y] = ndgrid(x, y);
P = [X(:), Y(:)];

The call to ndgrid will generate two matrices X and Y which will have the structure of the mesh you want, and the values X(i,j) and Y(i,j) correspond to each other. So to get the points P, you just need to reshape those arrays to column vectors and concatenate them.

Upvotes: 3

Related Questions