I'm writing code that receives quaternion values that are used to rotate a $3$D model. To display the model with the correct orientation, though, I'll need to swap the roll and pitch (rotation about the $x$ and $y$ axes). Since I can't change the code that produces the input quaternion, is it possible to swap the roll and pitch of a quaternion? I would like to do this without converting the quaternion to Euler angles to avoid issues if pitch is $90$ degrees.
In MATLAB, I converted various Euler angles to quaternions and then swapped the roll and pitch components of the Euler angles and converted that to quaternions. It's not obvious to me how to convert the original quaternion to the swapped version.
Let $q=a+bi+cj+dk\in \mathbb H$ be a quaternion and let us denote its imaginary part as a vector in $\mathbb R^3$: $$\left( \begin{matrix} b \\ c \\ d\end{matrix}\right) \in \mathbb R^3.$$
Then, we can apply the rotation matrices:
$${\displaystyle {\begin{alignedat}{1}R_{x}(\theta )&={\begin{pmatrix}1&0&0\\0&\cos \theta &-\sin \theta \\[3pt]0&\sin \theta &\cos \theta \\[3pt]\end{pmatrix},}\\[6pt]R_{y}(\theta )&={\begin{pmatrix}\cos \theta &0&\sin \theta \\[3pt]0&1&0\\[3pt]-\sin \theta &0&\cos \theta \\\end{pmatrix},}\\[6pt]R_{z}(\theta )&={\begin{pmatrix}\cos \theta &-\sin \theta &0\\[3pt]\sin \theta &\cos \theta &0\\[3pt]0&0&1\\\end{pmatrix},}\end{alignedat}}}$$
so that any rotation of angles $\alpha$, $\beta$, $\gamma$ in the $z$, $y$, $x$ directions respectively, can be expressed as the following product, which will give you a new vector:
$$R_{z}(\alpha )\,R_{y}(\beta )\,R_{x}(\gamma )\left( \begin{matrix} b \\ c \\ d\end{matrix}\right)= \left( \begin{matrix} \hat b \\ \hat c \\ \hat d\end{matrix}\right).$$
Then, your rotated quaternion will be $\hat q = a + \hat b i + \hat c j + \hat d k$.