Search code examples
matlab

Matlab - Plotting a sphere rotated about the y-axis


I am trying to produce the standard Matlab sphere plot, but with the vertical axis of the sphere tilted - as a model of the Earth rotating round the sun.

The code [X,Y,Z] = sphere(20) produces three 21x21 matrices of coordinates which I thought I could combine into a 21x21 matrix of x,y,z coordinate points. I then individually rotated each of these points around the y-axis by an angle theta using a standard rotation matrix, and re-extracted the rotated X, Y and Z matrices. I then used surf(rotX,rotY,rotZ) to create a plot.

Instead of giving a rotated sphere it produced a squashed sphere-like object:

squashed sphere

The purple line is the equator, rotated point by point using the rotation matrix, and the three straight lines are the axes from 0 to 2, with the x-axis in red.

Is there a problem with my logic here? When sphere(20) produces the three matrices are these the x,y,z coordinates of single points or are they combined in a more complicated way?

Grateful for assistance.

Here is the code

theta = -23;

% create rotation matrix
R = [cosd(theta), 0, sind(theta); 0, 1, 0; -sind(theta), 0, - cosd(theta)];

% draw sphere
[X,Y,Z] = sphere(20);

Xrot = zeros(length(X),length(X));
Yrot = zeros(length(X),length(X));
Zrot = zeros(length(X),length(X));

for cl = [1:1:columns(X)]
    for rw = [1:1:rows(X)]
       rot_pt = R * [X(cl,rw); Y(cl,rw); Z(cl,rw)];
       Xrot(cl,rw) = rot_pt(1);
       Yrot(cl,rw) = rot_pt(2);
       Zrot(cl,rw) = rot_pt(3);
    endfor
endfor

surf(Xrot,Yrot,Zrot)
colormap(summer)

Solution

  • The problem lies in the rotation matrix being applied. The [3,3] value, -cosd(theta) should not be negative. We can figure this out by referencing formulas, or simply by checking it against MATLAB's built-in rotation matrices.

    MATLAB makes rotation matrices simple with rotx(theta) etc. In this case, we can check if your rotation matrix is equal to roty(theta). Of course, you can also just use this function rather than creating the matrix.

    # Your Rotation Matrix
    R = [
        cosd(theta), 0, sind(theta); 
        0, 1, 0; 
        -sind(theta), 0, - cosd(theta)
    ];
    >> R =
        0.9205         0   -0.3907
        0    1.0000         0
        0.3907         0   -0.9205
    
    # Now Let's check the MATLAB Generated matrix
    R_ = roty(theta);
    >> R_ = 
        0.9205         0   -0.3907
             0    1.0000         0
        0.3907         0    0.9205
    

    If you either correct the negative, or replace R with R=roty(theta); The sphere will rotate around the y axis by the given angle. Usage of rotx() and rotz() is similar, if needed.