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?
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.