Rotating a 3D meshgrid with rotation matrix

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

 Accepted Answer

Matt J
Matt J on 19 May 2016
Edited: Matt J on 19 May 2016
temp=[X(:),Y(:),Z(:)]*R_zyx.' ;
sz=size(X);
Xrot=reshape(temp(:,1),sz);
Yrot=reshape(temp(:,2),sz);
Zrot=reshape(temp(:,3),sz);

4 Comments

Tomas commented:
Thank you very much for the quick answer!
That worked perfectly!
You're welcome.
sahar kheibarihafshejani's comment moved here:
Hello, i face same problem and wanna to rotate x,y,z position of my plane which each one has been saved in a seperate meshgrid. it seems this code works for me but i am too biginer in matlab can you explane this code alittle?
x(:) will sort al my x position in a just one culomn and then after rotation you reshape it in the previous meshgrid?
how can i make sure the elements will save in a right position?
Matt J
Matt J on 11 Sep 2020
Edited: Matt J on 11 Sep 2020
@sahar,
reshaping a Matlab array variable, whether using x(:) or reshape(x,___) has no reordering effect on the elements of x. The elements are stored in the same memory locations and in the same order, regardless of the fact that the variable referencing them has been reshaped.

Sign in to comment.

More Answers (0)

Categories

Asked:

on 19 May 2016

Edited:

on 11 Sep 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!