How To: Use Vectors, Matrices and Quaternions |
This section shows simple examples of how to calculate with vectors and matrices.
This topic contains the following sections:
Vector and matrix types belong to the namespace DigitalRune.Mathematics.Algebra. The following examples will also use the type MathHelper from the namespace DigitalRune.Mathematics. These namespace must be imported at the beginning of the source code file:
using DigitalRune.Mathematics; using DigitalRune.Mathematics.Algebra;
Next, we show how to rotate a vector around a given axis.
We define a vector v and a rotation axis:
Vector3F v = new Vector3F(1, 2, 3); Vector3F rotationAxis = Vector3F.UnitZ;
v is initialized as a vector (1, 2, 3). The vector rotationAxis is equal to the z unit vector (0, 0, 1).
Now, we can define a quaternion that rotates the vectors 30° around the rotation axis.
float rotationAngle = MathHelper.ToRadians(30); QuaternionF rotation = QuaternionF.CreateRotation(rotationAxis, rotationAngle);
Finally, we use the quaternion to rotate the vector v:
Vector3F vRotated = rotation.Rotate(v);
The same vector rotation as above can be achieved with a rotation matrix, like this:
Vector3F v = new Vector3F(1, 2, 3); Vector3F rotationAxis = Vector3F.UnitZ; float rotationAngle = MathHelper.ToRadians(50); Matrix33F rotation = Matrix33F.CreateRotation(rotationAxis, rotationAngle); Vector3F vRotated = rotation * v;
It is often necessary to compare vectors. In this example we create two vectors:
Vector3F v0 = new Vector3F(1000, 2000, 3000); QuaternionF rotation = QuaternionF.CreateRotationX(MathHelper.ToRadians(360)); Vector3F v1 = rotation.Rotate(v0);
The vector v1 is created by rotating v0 by 360° around the x-axis, which should result in the same vector. We can use the equality operator to compare the vectors:
if (v0 == v1) Console.WriteLine("Vectors are equal."); else Console.WriteLine("Vectors are not equal.");
This piece of code will output the message
Vectors are not equal.The vectors are considered not equal because the numerical errors in the rotation caused v1 to be (1000, 1999.99951, 3000.00049) instead of (1000, 2000, 3000). Numerical errors are inevitable. Therefore, we can use following code to check for equality with a numerical tolerance:
if (Vector3F.AreNumericallyEqual(v0, v1)) Console.WriteLine("Vectors are equal."); else Console.WriteLine("Vectors are not equal.")
This will output the message:
Vectors are equal.Other vector, matrix and quaternion types have similar methods for robust value comparison.