在matlab中绘制2D网格

时间:2014-09-13 05:31:30

标签: matlab plot

我正在尝试使用带有 x> = -1 y< = 1 的matlab获取2D网格,步长为0.1 但我得到的3D网格没有适当的步长。有什么想法吗?

我的代码:

[x, y] = meshgrid(-1:0.1:5, 0:0.1:1);
surf(x,y)

1 个答案:

答案 0 :(得分:3)

你只是想绘制一堆2D点吗?您使用plot。使用您的示例,您将获取x,y点并简单地为每个点添加点标记。在执行此操作之前,首先将它们转换为1D数组:

[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');

这就是我得到的:

enter image description here


根据评论进行编辑

如果要将此网格旋转一个角度,则可以使用旋转矩阵并将其与每对(x,y)坐标相乘。如果从线性代数中回忆一下,要逆时针旋转一个点,您将执行以下矩阵乘法:

[x'] = [cos(theta) -sin(theta)][x]
[y']   [sin(theta)  cos(theta)][y]

x,y是原始坐标,而x',y'是角度theta旋转后的输出坐标。如果要旋转-30度(顺时针旋转30度),则只需指定theta = -30 degrees。请记住,cossin将其角度视为弧度,因此实际上这是弧度中的-pi/6。您需要做的是将每个点放入2D矩阵中。然后,您将使用旋转矩阵并将其应用于每个点。这样,您就可以对解决方案进行矢量化,而不是......说...使用for循环。因此,你会这样做:

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');

这就是我得到的:

enter image description here

如果您想执行其他转换,例如缩放每个轴,您只需将XY坐标乘以适当的比例:

X_scaled = scale_x*X;
Y_scaled = scale_y*Y;

X_scaledY_scaled是您坐标的缩放版本,scale_xscale_y是您想要的每个维度的比例。如果你想翻译坐标,你可以用一些数字加上或减去每个维度:

X_translate = X + X_shift; %// Or -
Y_translate = Y + Y_shift; %// Or -

X_translateY_translate是已翻译的坐标,而X_shiftY_shift是每个维度所需的班次数量。请注意,您可以执行+-,具体取决于您的需求。