I tried your piece of code out to rotate a vector using a quaternion in Matlab, from the page:

http://www.martinb.com/maths/algebra/realNormedAlgebra/quaternions/transforms/index.htm

However, it was not working. I worked out the math and I think that for each of the terms involving 2*w in your code, the sign is the opposite of what it should be. I tried the following version of code out and it seems to function correctly:

p2.x = w*w*p1.x + x*x*p1.x - y*y*p1.x - z*z*p1.x + 2*(w*z*p1.y - w*y*p1.z + x*y*p1.y + x*z*p1.z);

p2.y = w*w*p1.y - x*x*p1.y + y*y*p1.y - z*z*p1.y + 2*(w*x*p1.z - w*z*p1.x + x*y*p1.x + y*z*p1.z);

p2.z = w*w*p1.z - x*x*p1.z - y*y*p1.z + z*z*p1.z + 2*(w*y*p1.x - w*x*p1.y + x*z*p1.x + y*z*p1.y);