在matlab中以2d的不同角度旋转矩阵

时间:2017-03-08 05:21:43

标签: matlab matrix rotation matlab-guide

我有一组数据点,我想在平面中逆时针旋转每个数据一个随机角度,在同一平面上的不同点。在第一次尝试中,我可以在平面中逆时针旋转它们在同一平面中的不同点之间的某个角度:

x = 16:25;
y = 31:40;
% create a matrix of these points, which will be useful in future  calculations
v = [x;y];
center = [6:15;1:10];
% define a 60 degree counter-clockwise rotation matrix
theta = pi/3;       % pi/3 radians = 60 degrees
R = [cos(theta) -sin(theta); sin(theta) cos(theta)];
% do the rotation...
vo = R*(v - center) + center;
% pick out the vectors of rotated x- and y-data
x_rotated = vo(1,:);
y_rotated = vo(2,:);
% make a plot
plot(x, y, 'k-', x_rotated, y_rotated, 'r-');

然后我尝试将其概括为随机天使旋转,但有一个问题我无法在第二个代码中解决:

x = 16:25;
y = 31:40;
% create a matrix of these points, which will be useful in future   calculations
v = [x;y];
center = [6:15;1:10]; %center of rotation
% define random degree counter-clockwise rotation matrix
theta = pi/3*(rand(10,1)-0.5);       % prandom angle 
R = [cos(theta) -sin(theta); sin(theta) cos(theta)];
% do the rotation...
 vo = R*(v - center) + center;
% pick out the vectors of rotated x- and y-data
x_rotated = vo(1,:);
y_rotated = vo(2,:);
% make a plot
plot(x, y, 'k-', x_rotated, y_rotated, 'r-');

问题是,当我尝试旋转矩阵时,旋转矩阵尺寸不应该如此。我不知道在这种情况下我应该如何创建旋转矩阵。 谁能建议如何解决这个问题?任何答案都非常感谢。

2 个答案:

答案 0 :(得分:1)

您的问题是您在R中创建了一个20x2矩阵。要了解原因,请考虑

theta % is a 10x1 vector

cos(theta)  % is also going to be a 10x1 vector

[cos(theta) -sin(theta);...
 sin(theta) cos(theta)];  % is going to be a 2x2 matrix of 10x1 vectors, or a 20x2 matrix

您想要的是访问每个2x2旋转矩阵。一种方法是

R1 = [cos(theta) -sin(theta)] % Create a 10x2 matrix
R2 = [sin(theta) cos(theta)] % Create a 10x2 matrix

R = cat(3,R1,R2) % Cocatenate ("paste") both matrix along the 3 dimension creating a 10x2x2 matrix

R = permute(R,[3,2,1]) % Shift dimensions so the matrix shape is 2x2x10, this will be helpful in the next step.

现在您需要将每个数据点乘以其对应的旋转矩阵。乘法仅针对2D矩阵定义,因此我不知道更好的方法,而不是遍历每个点。

for i = 1:length(v)
    vo(:,i) = R(:,:,i)*(v(:,i) - center(:,i)) + center(:,i);
end

答案 1 :(得分:0)

为什么不用imrotate旋转。

例如,您想要旋转30度:

newmat = imrotate(mat, 30, 'crop')

顺时针旋转30度并保持尺寸相同。要增加尺寸,您可以使用'full'

中的imresize选项

在旋转矩阵中输入随机值

rn = rand*90; %0-90 degrees
newmat = imrotate(mat, rn, 'crop')