MATLAB同时旋转和移动2d对象

时间:2013-04-05 15:36:10

标签: matlab animation

我使用此代码制作了明星:

t = 0:4/5*pi:4*pi;
x = sin(t);
y = cos(t);
star = plot(x, y);
axis([-1 11 -1 11])

现在我需要同时旋转和移动这颗星。我试过这个:

for i=1:0.1:10;
    zAxis = [0 0 1];
    center = [0 0 0];
    rotate(star, zAxis, 5, center);
    x = x+0.1;
    y = y+0.1;
    set(star, 'x', x, 'y', y);
    pause(0.1);
end

但是这段代码只会移动星号并且不会旋转它。如果我删除“set”命令然后它旋转。我怎样才能将这两个行动结合起来?

2 个答案:

答案 0 :(得分:1)

这可以胜任......

t = 0:4/5*pi:4*pi;
x = sin(t);
y = cos(t) ;
y = y-mean(y);
x = x-mean(x);  % # barycentric coordinates

% # rotation and translation 
trasl = @(dx,dy) [dy; dx];  % # this vector will be rigidly added to each point of the system
rot = @(theta)  [cos(theta) -sin(theta); sin(theta) cos(theta)];  % # this will provide rotation of angle theta


for i = 1:50
    % # application of the roto-translation
    % # a diagonal translation of x = i*.1 , y = i*.1 is added to the star
    % # once a rotation of angle i*pi/50 is performed
    x_t = bsxfun(@plus,rot(i*pi/50)*([x;y]), trasl(i*.1,i*.1) );  

    star = plot(x_t(1,:), x_t(2,:));
    axis([-1 11 -1 11])
    pause(.1)

end

原则上,homogeneous coordinates(在 2D投影空间中)允许人们以更整洁的方式完成同样的工作;事实上,他们只允许使用一个线性算子(3x3矩阵)。

同构坐标版本:

Op = @(theta,dx,dy) [ rot(theta) , trasl(dx,dy) ; 0 0 1];

for i = 1:50
   x_t = Op(i*pi/50,i*.1,i*.1)*[x;y;ones(size(x))];

    star = plot(x_t(1,:), x_t(2,:));
    axis([-1 11 -1 11])
    pause(.1)    
end

答案 1 :(得分:0)

您可以使用rotation matrix计算向量[x; y]上的正确转换:

theta = 5 * (pi / 180); % 5 deg in radians
Arot = [cos(theta) -sin(theta); sin(theta) cos(theta)];
xyRot = Arot * [x; y]; % rotates the points by theta
xyTrans = xyRot + 0.1; % translates all points by 0.1
set(star, 'x', xyTrans(1, :), 'y', xyTrans(2, :));