MATLAB: How to rotate ANY vector to a given angle in the space

MATLABrotation vector angle 3d space

I would like to rotate the source vector to be a dot from upper view (xy plane). How is it possible in Matlab?
E.g.: There is a vector: X = [0 4]; Y = [0 4]; Z = [0 0];
This is a 45° line in the xy plane. If a rotation is made around the z-axis with 45°, then 90° around the y-axis, it gives the result, what I would like to achive in ANY vector.
Due to compatibility with other softwares, it's important to rotate only around the Y and Z axis.
Can anybody help?

Best Answer

I am assuming that what you want to know are the rotation angles that would be used to perform a Z-Y rotation sequence in order to align a general vector with the Z axis. I will assume that the general vector is defined by it's tail point, P1, and it's head point P2. This vector points from P1 to P2.
The first thing that needs to happen is to translate this vector to the origin. This is done by subtracting the tail from the head, i.e. V = P2 - P1.
We now have a vector V with it's tail at the origin. We will perform a Z rotation through the angle psi which will place the vector in the X-Z plane, as in the first figure, below. The angle of rotation is computed from the X and Y components of the vector using Tan(psi) = -Vy / Vx. Notice in the figure that using a positive value for Vy and the right-hand rule for vector rotation, the rotation angle in the figure is negative, therefore, we put a negative sign on Vy.
With the vector rotated to position (2), it is now in the X-Z plane. Now we want to rotate through the angle theta to align it with the Z axis. The angle theta is calculated according to cos(theta) = -Vz / mag(V). Once again, using the right-hand rule, this is a negative rotation angle.