Reputation: 347
I am trying to get a 2D grid using matlab with x >= -1 and y <= 1 with step size of 0.1 But I'm getting 3D grid with no proper step sizes. Any ideas?
My code:
[x, y] = meshgrid(-1:0.1:5, 0:0.1:1);
surf(x,y)
Upvotes: 1
Views: 6069
Reputation: 104464
Do you just want to plot a bunch of 2D points? You use plot
. Using your example, you would take your x,y
points and simply put dot markers for each point. Convert them into 1D arrays first before you do this:
[X,Y] = meshgrid(-1:0.1:5, 0:0.1:1);
X = X(:);
Y = Y(:);
plot(X,Y,'b.');
xlabel('X'); % // Label the X and Y axes
ylabel('Y');
This is what I get:
If you want to rotate this grid by an angle, you would use a rotation matrix and multiply this with each pair of (x,y)
co-ordinates. If you recall from linear algebra, to rotate a point counter-clockwise, you would perform the following matrix multiplication:
[x'] = [cos(theta) -sin(theta)][x]
[y'] [sin(theta) cos(theta)][y]
x,y
are the original co-ordinates while x',y'
are the output co-ordinates after rotation of an angle theta
. If you want to rotate -30 degrees (which is 30 degrees clockwise), you would just specify theta = -30 degrees
. Bear in mind that cos
and sin
take in their angles as radians, so this is actually -pi/6
in radians. What you need to do is place each of your points into a 2D matrix. You would then use the rotation matrix and apply it to each point. This way, you're vectorizing the solution instead of... say... using a for
loop. Therefore, you would do this:
theta = -pi/6; % // Define rotation angle
rot = [cos(theta) -sin(theta); sin(theta) cos(theta)]; %// Define rotation matrix
rotate_val = rot*[X Y].'; %// Rotate each of the points
X_rotate = rotate_val(1,:); %// Separate each rotated dimension
Y_rotate = rotate_val(2,:);
plot(X_rotate, Y_rotate, 'b.'); %// Show the plot
xlabel('X');
ylabel('Y');
This is what I get:
If you wanted to perform other transformations, like scaling each axis, you would just multiply either the X
or Y
co-ordinates by an appropriate scale:
X_scaled = scale_x*X;
Y_scaled = scale_y*Y;
X_scaled
and Y_scaled
are the scaled versions of your co-ordinates, with scale_x
and scale_y
are the scales in each dimension you want. If you wanted to translate the co-ordinates, you would add or subtract each of the dimensions by some number:
X_translate = X + X_shift; %// Or -
Y_translate = Y + Y_shift; %// Or -
X_translate
and Y_translate
are the translated co-ordinates, while X_shift
and Y_shift
are the amount of shifts you want per dimension. Note that you either do +
or -
, depending on what you want.
Upvotes: 3