MATLAB: Rotate a cube and the translation of it

geometric transformations

I was asked to draw a cube and make it rotate around a given axis and to make a translation of it away from origo. Then rotate it again for a given a axis.
My code so far:
H=[0 0.3 0 0.3 0 0.3 0 0.3; 0 0 0.3 0.3 0 0 0.3 0.3; 0 0 0 0 0.3 0.3 0.3 0.3];
S=[1 2 4 3; 1 2 6 5; 1 3 7 5; 3 4 8 7; 2 4 8 6; 5 6 8 7];
figure(1), clf, hold on
for i=1:size(S,1)
Si=S(i,:); fill3(H(1,Si),H(2,Si),H(3,Si),'g','facealpha',0.6)
end
axis equal, axis on, hold off, view(20,10)

Best Answer

H=[0 0.3 0 0.3 0 0.3 0 0.3; 0 0 0.3 0.3 0 0 0.3 0.3; 0 0 0 0 0.3 0.3 0.3 0.3];
S=[1 2 4 3; 1 2 6 5; 1 3 7 5; 3 4 8 7; 2 4 8 6; 5 6 8 7];
figure(1)
hold on
H1 = zeros(size(S,1),4) ;
H2 = zeros(size(S,1),4) ;
H3 = zeros(size(S,1),4) ;
for i=1:size(S,1)
Si=S(i,:);
fill3(H(1,Si),H(2,Si),H(3,Si),'g','facealpha',0.6)
end
axis equal, axis on, hold off, view(20,10)
%%Rotation along x axes
th = linspace(0,2*pi) ;
for i = 1:length(th)
Rx = [1 0 0 ; 0 cos(th(i)) -sin(th(i)); 0 sin(th(i)) cos(th(i))] ;
%%Rotae the vertices
H1 = zeros(size(H)) ;
for j = 1:size(H,2)
H1(:,j) = Rx*H(:,j) ;
end
for k=1:size(S,1)
Si=S(k,:);
fill3(H1(1,Si),H1(2,Si),H1(3,Si),'g','facealpha',0.6)
hold on
end
drawnow
hold off
end
Note that the above code can be vectorized and made simple, but for your understanding I have added the rotation part in the way you have plotted the cube. In the same lines you can follow translation too.
Related Question