MATLAB: Rotating a 3D meshgrid with rotation matrix

3dmeshgridrotation matrixthree dimensions

Hello,
I would like to rotate 3D coordinates in a meshgrid. I managed to do what I want, but I'm thinking there is a much smarter way than to go with three for-loops, which becomes very slow. Is there somebody that knows how to go about?
[Y,X,Z] = meshgrid(-Ny:Ny,-Nx:Nx,-Nz:Nz);
Xrot=zeros(size(X));
Yrot=zeros(size(Y));
Zrot=zeros(size(Z));
%
c1=cos(theta);
c2=cos(phi);
c3=cos(gamma);
s1=sin(theta);
s2=sin(phi);
s3=sin(gamma);
R_zyx=[c1*c2 c1*s2*s3-c3*s1 s1*s3+c1*c3*s2;
c2*s1 c1*c3+s1*s2*s3 c3*s1*s2-c1*s3;
-s2 c2*s3 c2*c3];
for i=1:2*Nx+1
for j=1:2*Ny+1
for k=1:2*Nz+1
temp=R_zyx*[X(i,j,k) Y(i,j,k) Z(i,j,k)]';
Xrot(i,j,k)=temp(1);
Yrot(i,j,k)=temp(2);
Zrot(i,j,k)=temp(3);
end
end
end

Best Answer

temp=[X(:),Y(:),Z(:)]*R_zyx.' ;
sz=size(X);
Xrot=reshape(temp(:,1),sz);
Yrot=reshape(temp(:,2),sz);
Zrot=reshape(temp(:,3),sz);