As the title says, i have a problem to convert a Quaternion
to a Matrix4f
. Eigen
has the method Quaternion.toRotationMatrix()
which gives me a Matrix3f
.
Now i need a Matrix4f
( because our program is designed to take only Matrix4f
), is there an easy way to achieve this?

- 5,627
- 2
- 21
- 28

- 1,257
- 3
- 20
- 33
-
2It depends on the application, but you could try creating the `Matrix4f` with the 3 components of the `Matrix3f`, plus a `1` as the 4th (`w`) component. But as I said, it definitely depends on the application - not all quaternions even represent rotation matrices. – Rob I Apr 02 '13 at 12:54
-
1I second Rob I's comment. Most matrix implementations take the 4th column "as position vector" and the 4th row as the "scaling". – Najzero Apr 02 '13 at 12:57
2 Answers
@Zacharias' answer contains the necessary theory. I just reiterate my earlier comment I made there with the actual Eigen C++ code.
Eigen::Matrix3f mat3 = Eigen::Quaternionf(W, X, Y, Z).toRotationMatrix();
Eigen::Matrix4f mat4 = Eigen::Matrix4f::Identity();
mat4.block(0,0,3,3) = mat3;
Eigen::Matrix4f::Identity()
takes care of initializing the ones and zeros of the 4th and last row and column. mat4.block(0,0,3,3) = mat3
then overwrites the values obtained from the rotation matrix.

- 966
- 1
- 10
- 22
M3 to M4
The answere is already there, given by Rob and Najzero. In most cases, it will be sufficient to construct the matrix as follows:
m3:
|a00|a01|a02|
|a10|a11|a12|
|a20|a21|a22|
to m4:
|a00|a01|a02| 0 |
|a10|a11|a12| 0 |
|a20|a21|a22| 0 |
| 0 | 0 | 0 | 1 |
The 4x4 matrix does not only allow to rotate a vector, but also to shift(translate) and scale (in all 3 directions) any vector. So basically you got a full transformation matrix - thats why it is often used in computer graphics, describing the transformation of an object. Depending on row-column order, we might identify the matrix as:
|rot|rot|rot| sx |
|rot|rot|rot| sy |
|rot|rot|rot| sz |
| x | y | z | 1 |
with sx,sy,sz as scaling coefficients, and x,y,z as translation coefficients.
PS: of course, if you want to rotate a vector with m4, you will than have to use a 4-dimensional vector, e.g. (x,y,z,w) with w=1 (in most cases).
The direct approach
Convert Quaternion rotation to rotation matrix?
And my personal recommendation: http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToMatrix/ There you will find also other transformations, backtrafos and so on.
-
4`Eigen::Matrix3f mat3 = Eigen::Quaternionf(W, X, Y, Z).toRotationMatrix(); Eigen::Matrix4f mat4 = Eigen::Matrix4f::Identity(); mat4.block(0,0,3,3) = mat3;` – user1556435 Feb 25 '16 at 12:23
-