MATLAB: Creating a matrix using a loop

matrix manipulation

Hi,
I am struggling with probably a very simple problem. I want to build a matrix. My X coordinate runs from -2 to 2 with increment 1 and same with Y. I want to create a matrix that will be following: x: -2 -1 0 1 2 Y: -2 -2 -2 -2 -2, then goes on X: -2 -1 0 1 2, Y= -1 -1 -1 -1 -1 and continues until X= -2 -1 0 1 2 , Y=2 2 2 2 2.
This means for same X positions Y varies from -2 to 2. I dont know how to do that. Could anybody please help me on this.
Thanks,
Rafiq

Best Answer

[xx,yy]=ndgrid( -2:1:2, -2:1:2);
xy = [xx(:), yy(:)];
x = xy(:,1);
y = xy(:,2);