How to turn CMRotationmatrix to initial position - swift

I have a rotation matrix that I get from the motion manager. It rotates an object. Now I want to reset the Rotation, meaning that I press a button on the iPhone and the rotation is set back to the start without turning the iPhone to the start position.
I was able to achieve this by saving the initial values of m11 to m33 of the rotation matrix to an array and do this: (current position m11 to m33) - (position when pressing the reset button m11 to m33 - initial position of m11 to m33).
This leads to the current rotation matrix having the exact values as the initial matrix and therefore resetting the rotation. However, if I now turn the iPhone the resulting turning of the object is nonsense as are the values of the rotation matrix.
So what is the proper formula of calculating this / What is the formula to turn back the rotation matrix as many degrees in x/y/z as the iPhone has been turned until now?
Thanks a lot.

The answer is to take the initial transformation matrix and divide every new transformation matrix by it. My problem was that I did the calculation wrong. So a look at how to divide by a matrix helped.

Related

Unity Rotate Sphere To Point Directly Upwards Based On Child Point

I've got a 3d sphere which I've been able to plot a point on using longitude and latitude thanks to some work of another developer I've found online. I think I understand what its doing.
What I need to do now is rotate my planet so the point is always at the top most point (ie the north pole) but I'm not sure how to do this. I'm probably missing some important fundamentals here so I'm hoping the answer can assist in my future learning.
Here's an image showing what I have - The blue line is a line coming from the longitude and latitude I have plotted and I need to rotate the planet so that line is basically pointing directly upwards.
https://ibb.co/2y24FxS
If anyone is able to advise it'd be very much appreciated.
If I'm not mistaken, Unity uses a coordinate system where the y-axis points up.
If the point on your sphere was in the xy-plane, you'd just have to determine the angle between the radius-vector (starts in the center of the sphere, ends on the point in question) and the y-axis, and than rotate by that amount around the z-axis, so that the radius vector becomes vertical. But your point is at an arbitrary location in 3D space - see the image below. So one way to go about it is to first bring the point to the xy-plane, then continue from there.
Calculate the radius vector, which is just r = x-sphereCenter. Make a copy of it, set y to zero, so that you have (x, 0, z) - which is just the projection of the vector r on the horizontal xz-plane - let's call the copy rXZ.
Determine the signed angle between the x-axis and rXZ (use Vector3.SignedAngle(xAxis, rXZ, yAxis), see docs), and create a rotation matrix M1 that rotates the sphere in the opposite direction around the vertical (negate the angle). This should place your point in the xy-plane.
Now determine the angle between r and the y-axis (Vector3.SignedAngle(r, yAxis, zAxis)), and create a new rotation matrix M2 that rotates by that angle around the zAxis. (I think for this second one, the simpler Vector3.Angle will work as well.)
So, what you want now is to combine the two matrices (by multiplying them) into a single transform (I'm assuming this is a transformation in the local coordinate system of the sphere, where (0, 0, 0) is the sphere's center). If I'm not mistaken, Unity uses column-major matrices, so the multiplication order should be M = M2 * M1 (the rightmost matrix is applied first).
Reorient your globe using M as a local transform, and it should bring your point to the top. You can also create M3 = M1.inverse, and then do M = M3 * M2 * M1, to preserve the original angular offset from the xy-plane.
Check for edge cases, such as r already being vertical (pointing straight up, or straight down).

Computing Euler angles from rotation matrix: boundary cases

I want to compute the Euler angles from a rotation matrix in order to find out the orientation associated to that rotation. For that purpose, I am using MATLAB and the function rotm2eul that gives me the rotation first about x-axis, then about y-axis and finally the z-axis.
I am using a signal with 1000 frames and for each frame a rotation matrix is computed, as well, the three Euler angles. However, when I am going to see the Euler angles' curve, there is some "jumps" as I shown on the figures below.
On Technique 1, I think it jumps from -180º to 180º which should be the same. In fact, the upper portion of the plot seems a continuation of the lower portion. So in this case I thought I could subtract 360º to the upper portion to get the plot. But I am not sure if I do this I am falsifying the results.
On Technique 2, it makes a jump with a different reason of the previous one. I think it must be because the angle associated with the y-axis reaches 90º which should be a boundary case. But in this case I don't know how should I correct the data or , like previously, if I want to correct the plot is falsifying the euler angle result.
Technique 2: This is a Gimbal lock, known feature of Euler angles. You can't avoid it completely. You can change the rotation order, but it will appear in another position.

Azimuth and Elevation from one moving object to another, relative to first object's orientation

I have two moving objects with position and orientation data (Euler Angles, Quaternions) relative to ECI coordinate frame. I would like to calculate AZ/EL from what I'm guessing is the "body frame" of the first object. I have attempted to convert both objects into the body frame through rotation matrices (X-Y-Z and Z-Y-X rotation sequence) and calculate a target vector AZ/EL this way but have not had success. I've also tried to get body frame positions and calculate the body axis/angles and convert back to Eulers (relative to body frame). I'm never sure how the coordinate system axes I'm supposedly creating are aligned along my object.
I have found a couple other questions like this answered with Quaternion solutions so that may be the best path to take, however my Quaternion background is weak at best and I fail to see how the computations given result in a target vector.
Any advice would be much appreciated and I'm happy to share my progress/experiences going forward.
get the current NEH transform matrix for the moving object
you must know position and at least two directions from North,East,Height(Up or Altitude) of the moving object otherwise is your problem unsolvable no matter what. This matrix/frame is called NEH (X=North,Y=East,Z=Height) or sometimes also ENU (X=East,Y=North,Z=Up). Look here transform matrix anatomy and here Earth's NEH construction and change the position and radius to match your moving object.
convert point P0 from GCS (global coordinate system) to NEH
simply: P1=Inverse(NEH)*P0 where P1 is now in NEH LCS (Local coordinate system). Both P0,P1 are in homogenous coordinates { x,y,z,w=1 } to allow multiplications with 4x4 matrix so you can compute azimut and elevation directly from it:
Azimut=atanxy(P1.x,P1.y);
Elevation=atan(P1.z/sqrt((P1.x*P1.x)+(P1.y*P1.y)));
where atanxy is mine atan2 (4 quadrant atan) first is dx then dy. I think atan2 in matlab has it in reverse.
[Notes]
Always visually check all frames (especially NEH). Just draw the 3 axises as lines of some length to validate if the result is correct. It should look like on image, just different color for each axis. You can move to next point only if NEH is OK !!!
Check atan2/atanxy operands order and also check goniometric functions units (rad,deg) to avoid confusions.

How to calculate yxy rotation sequence given the quaternion transformation and how to interpret data

Still need the math: I am trying to calculate the yxy rotation sequence given a quaternion transformation. I can easily do this using Matlab's quat2angle function. However, I need to calculate this by hand using a python script.
This part solved: Please look at this awesome presentation which helped me resolve these issues below:
https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0CCoQFjAC&url=http%3A%2F%2Fwww.udel.edu%2Fbiology%2Frosewc%2Fkaap686%2Freserve%2Fshoulder%2Fshoulder%2FBluePresentation.ppt&ei=jgRAVLHfOsSrogTJiYHABQ&usg=AFQjCNGFmwh11jEZen80jc3tM4f7HUQcNw&sig2=Dlr8_7TIFPLyUfJy6-pSJA&bvm=bv.77648437,d.cGU
Also, with Matlab, I am seeing strange results with the way they calculate yxy. I have a quaternion transformation of [1.0000 -0.0002 -0.0011 -0.0006] and I get y = 112.4291 x = -0.0719 y1 = -112.5506 (in degrees).
I don't expect to see any rotations here (my sensors aren't rotating). Why is Matlab showing me rotation? And when I try to just move in the x rotation, I see y and y1 also rotate, however, I don't expect y or y1 to be rotating. Any thoughts?
UPDATE:
When I add y + y1 I seem to get the value for the first y (when doing simple rotation around the first y), and this smooths out the data. However, when I combine the three rotations of the shoulder, the data doesn't make sense. I am trying to define shoulder movement based on plane of elevation, elevation and rotation (yxy) in a way that's easy to interpret. When I rotate around x, then the second y, I get "clipping" (data goes to 180 then -180 following positive trend for y1 and opposite happens for y), even though I start my sensors at the zero position. Also, If I try to rotate only around the second y, I see rotation in the x. That doesn't make any sense either. Any additional thoughts?
Note:
I am using 2 IMU sensors, taring them in the same orientation, holding one constant and rotating the other, calculating the relative rotation between them using quaternions, and then calculating the yxy rotation sequence angles.
In case anyone is interested in quaternion calculations and transformations. I solved it using this transformations library:
http://www.lfd.uci.edu/~gohlke/code/transformations.py.html
There are several functions in here using matrices, quaternions, and Euler rotations. And you can convert quaternions to several different Euler rotation sequences. Give thanks to the person who created this script.

Matlab matrix translation and rotation multiple times

I have a map of individual trees from a forest stored as x,y points in a matrix. I call it fixedPositions. It's cartesian and (0,0) is the origin.
Given a velocity and a heading, i.e. .5 m/s and 60 degrees (2 o'clock equivalent on a watch), how do I rotate the x,y points, so that the new origin is centered at (.5cos(60),.5sin(60)) and 60 degrees is now at the top of the screen?
Then if I were to give you another heading and speed, i.e. 0 degrees and 2m/s, it should calculate it from the last point, not the original fixedPositions origin.
I've wasted my day trying to figure this out. I wish I took matrix algebra but I'm at a loss.
I tried doing cos(30) and even those wouldn't compute correctly, which after an hour I realize were in radians.
I'd try the following: In your object, you already have a property heading. Now you add another property, currentPosition (an maybe rename them to heading_robot and currentPos_robot). heading as well as currentPosition should always be relative to the original coordinate system
Then you add a new method, updatePosition that takes (newHeading, distance) as input. This method will update both heading and currentPosition, by first adding the angle in newHeading to the angle in heading, after which you update currentPosition by adding [distance*cos(heading),distance*sin(heading)] (check for signs of sin/cos here!) to the old value of currentPosition.
Finally, to get the view of the landscape (i.e. apparentPositions), you run bsxfun(#minus,fixedPositions,currentPosition) to move the origin to where the robot is at this moment, and then you multiply with the 2D rotation matrix using the angle stored in heading.
You just first translate the coordinates (-0.5cos(60),-0.5sin(60)) to take the origin to your target point.
Then rotate by multiplying the coordinates by a rotation matrix.
Of course, most programming languages use radians as angle units, so that instead of 60 you must enter 60 * PI / 180