78d04f1seqlab: write and view pulseq MRI sequences in the browserJeremy Magland 1function r = rotate(q,v)
2%ROTATE rotate vector v by quaternion q
3% Rotation ov a vector v by a unit quaternion q can be expressed as qvq',
4% where v is temporarily transformed to a quaternion of a form [0 v]. The
5% function below spells it out explicitly to accelerate calculations
7% A simple quaternion product can be calculated for the vector and scalar
8% parts of the quaternion as follows:
9% vec = s1*v2 + s2*v1 + cross(v1,v2)
10% scalar = s1*s2 - dot(v1,v2)
11% We redefine variables as s1=sq=q(0), v1=vq=q(2:4), s2=0, v2=v
12% The first part of the product can be writtes as
13% vec1= sq*v + cross(vq,v)
14% scl1= -dot(vq,v)
15% The second part of the product is then
16% vec2= -scl1*vq + sq*vec1 + cross(vec1,-vq)
17% scl2= scl1*sq - dot(vec1,-vq)
18% but actually scl2 sould be discarded so we don't calculate it
20% here is what ChatGPT derives
21%r1=(q1^2+q2^2−q3^2−q4^2)*v1+2*(q2*q3−q1*q4)*v2+2*(q2*q4+q1*q3)*v3
22%r2=2*(q2*q3+q1*q4)*v1+(q1^2−q2^2+q3^2−q4^2)*v2+2*(q3*q4−q1*q2)*v3
23%r3=2*(q2*q4−q1*q3)*v1+2*(q3*q4+q1*q2)*v2+(q1^2−q2^2−q3^2+q4^2)*v3
25r = [(q(:,1)^2 + q(:,2)^2 - q(:,3)^2 - q(:,4)^2)*v(:,1) + 2*(q(:,2)*q(:,3) - q(:,1)*q(:,4))*v(:,2) + 2*(q(:,2)*q(:,4) + q(:,1)*q(:,3))*v(:,3) ...
26 2*(q(:,2)*q(:,3) + q(:,1)*q(:,4))*v(:,1) + (q(:,1)^2 - q(:,2)^2 + q(:,3)^2 - q(:,4)^2)*v(:,2) + 2*(q(:,3)*q(:,4) - q(:,1)*q(:,2))*v(:,3) ...
27 2*(q(:,2)*q(:,4) - q(:,1)*q(:,3))*v(:,1) + 2*(q(:,3)*q(:,4) + q(:,1)*q(:,2))*v(:,2) + (q(:,1)^2 - q(:,2)^2 - q(:,3)^2 + q(:,4)^2)*v(:,3) ];
29end