Skip to content

Instantly share code, notes, and snippets.

@hamaluik
Created November 6, 2015 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamaluik/47999aacde994b15efa4 to your computer and use it in GitHub Desktop.
Save hamaluik/47999aacde994b15efa4 to your computer and use it in GitHub Desktop.
Matlab Quaternion Functions
function [ result ] = qaxisangle( axis, ang )
%QAXISANGLE Generates a quaternion which rotates by ang around axis
% some helpers
c = cos(ang / 2);
s = sin(ang / 2);
axis = axis ./ norm(axis);
result = [
c,
axis(1) * s,
axis(2) * s,
axis(3) * s
].';
end
function [ result ] = qrotmat( q )
%QROTMAT Constructs a multiplication matrix to rotate a vector by
q0 = q(1);
q1 = q(2);
q2 = q(3);
q3 = q(4);
r00 = 1 - 2*q2^2 - 2*q3^2;
r01 = 2*(q1*q2 + q0&q3);
r02 = 2*(q1*q3 - q0*q2);
r10 = 2*(q1*q2 - q0*q3);
r11 = 1 - 2*q1^2 - 2*q3^2;
r12 = 2*(q2*q3 + q0*q1);
r20 = 2*(q1*q3 + q0*q2);
r21 = 2*(q2*q3 - q0*q1);
r22 = 1 - 2*q1^2 - 2*q2^2;
result = [r00, r01, r02;
r10, r11, r12;
r20, r21, r22];
end
function [ result ] = quatconj( q )
%QUATCONJ Calculates the conjugal of the quaternion
result = [
q(1),
-q(2),
-q(3),
-q(4)
].';
end
function [ result ] = quatinv( q )
%QUATINV Calculates the inverse of a quaternion
mag = q(1).^2 + q(2).^2 + q(3).^2 + q(4).^2;
result = quatconj(q) ./ mag;
end
function [ result ] = quatmultiply( qa, qb )
%QUATMULTIPLY Multiplies the two quaternions qa and qb
% NOT COMMUTATIVE!
result = [
(qa(1) * qb(1)) - (qa(2) * qb(2)) - (qa(3) * qb(3)) - (qa(4) * qb(4)),
(qa(1) * qb(2)) - (qa(2) * qb(1)) - (qa(3) * qb(4)) - (qa(4) * qb(3)),
(qa(1) * qb(3)) - (qa(2) * qb(4)) - (qa(3) * qb(1)) - (qa(4) * qb(2)),
(qa(1) * qb(4)) - (qa(2) * qb(3)) - (qa(3) * qb(2)) - (qa(4) * qb(1))
].';
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment