# 关于在坐标系中旋转平移物体的编程实现Matlab, Python

## 代码放出

### 平移物体

%%%MATLAB
function [X2, Y2, Z2] = Move(a, x, X1, Y1, Z1)

%确定坐标轴与位移矩阵
if a == 1
move = [x; 0; 0];
else if a == 2
move = [0; x; 0];
else if a == 3
move = [0; 0; x];
end
end
end

%矩阵的大小与初始化操作后的矩阵
l = size(X1);
X2 = zeros(size(X1));
Y2 = zeros(size(Y1));
Z2 = zeros(size(Z1));

%对每一行进行操作
for i = 1:l(1)
temp = [X1(i,:); Y1(i,:); Z1(i,:)] + move*ones(1, l(2));
X2(i,:) = temp(1,:);
Y2(i,:) = temp(2,:);
Z2(i,:) = temp(3,:);
end

end

Python的逻辑相同

###Python
def Move(a, x, X1, Y1, Z1):
'''对坐标进行平移操作'''
#确定坐标轴与位移矩阵
if a == 1:
move = np.array([[x], [0], [0]])
elif a == 2:
move = np.array([[0], [x], [0]])
elif a == 3:
move = np.array([[0], [0], [x]])

#数组的大小
s = X1.shape

#初始化操作后的数组
X2, Y2, Z2 = [np.zeros(s) for i in range(3)]

for i in range(s[0]):
#进行操作
temp = np.vstack((X1[i,:], Y1[i,:], Z1[i,:])) + move*np.ones(s[1])
X2[i,:] = temp[0,:]
Y2[i,:] = temp[1,:]
Z2[i,:] = temp[2,:]
return X2, Y2, Z2

### 旋转物体

%%%MATLAB
function [X2, Y2, Z2] = Rotate(a, theta, X1, Y1, Z1)

%确定坐标轴与旋转矩阵
if a == 1
rotate = [1 0 0; 0 cos(theta) sin(theta); 0 -sin(theta) cos(theta)];
else if a == 2
rotate = [cos(theta) 0 -sin(theta); 0 1 0; sin(theta) 0 cos(theta)];
else if a == 3
rotate = [cos(theta) sin(theta) 0; -sin(theta) cos(theta) 0; 0 0 1];
end
end
end

%矩阵的大小与初始化操作后的矩阵
l = size(X1);
X2 = zeros(size(X1));
Y2 = zeros(size(Y1));
Z2 = zeros(size(Z1));

%对每一行进行操作
for i = 1:l(1)
temp = rotate*[X1(i,:); Y1(i,:); Z1(i,:)];
X2(i,:) = temp(1,:);
Y2(i,:) = temp(2,:);
Z2(i,:) = temp(3,:);
end

end

###Python
def Rotate(a, theta, X1, Y1, Z1):
'''对坐标进行旋转操作'''
if a == 1:
rotate = np.array([[1, 0, 0], [0, np.cos(theta), np.sin(theta)], [0, -np.sin(theta), np.cos(theta)]])
elif a == 2:
rotate = np.array([[np.cos(theta), 0, -np.sin(theta)], [0, 1, 0], [np.sin(theta), 0, np.cos(theta)]])
elif a == 3:
rotate = np.array([[np.cos(theta), np.sin(theta), 0], [-np.sin(theta), np.cos(theta), 0], [0, 0, 1]])

s = X1. shape
X2, Y2, Z2 = [np.zeros(s) for i in range(3)]

for i in range(s[0]):
temp = np.dot(rotate,np.vstack((X1[i,:], Y1[i,:], Z1[i,:])))
X2[i,:] = temp[0,:]
Y2[i,:] = temp[1,:]
Z2[i,:] = temp[2,:]
return X2, Y2, Z2

### 主函数

%%%MATLAB
clc, clear, close all

figure(1)
%做坐标轴
plot3([0 0], [0 0], [0 2], 'k', 'LineWidth', 2)
axis([-2 2 0 2 -2 2])
hold on
grid on
plot3([0 2], [0 0], [0 0], 'k', 'LineWidth', 2)
plot3([0 0], [0 2], [0 0], 'k', 'LineWidth', 2)
xlabel('x')
ylabel('y')
zlabel('z')
%做旋转轴
y_ = 0:0.1:2;
z_ = y_-1;
x_ = zeros(size(y_));
plot3(x_, y_, z_)

%初始化各种数据
x = 0:0.1:1;
y = 0:0.1:1;
[X, Y] = meshgrid(x, y);
Z = X+Y;

%画原位置物体
surf(X, Y, Z)

%操作一，平移
[X1, Y1, Z1] = Move(2, -1, X, Y, Z);
%操作二，旋转
[X2, Y2, Z2] = Rotate(1, pi/4, X1, Y1, Z1);
[X3, Y3, Z3] = Rotate(2, pi, X2, Y2, Z2);
[X4, Y4, Z4] = Rotate(1, -pi/4, X3, Y3, Z3);
[X5, Y5, Z5] = Move(2, 1, X4, Y4, Z4);

%画旋转后的物体
surf(X5, Y5, Z5)

Python的逻辑同理，但是因为我Python作图不是很熟，所以就没有作图了，有兴趣的朋友可以自己做一下试试。