MATLAB: Is the function returning these error messages

errorfunctionMATLABmatrix

I am new to matlab, and though I am versed in java as a language this is my first time writing code in a context such as this one.
For context, this code is an attempt at the creation of a function that would rotate an input 3d coordinate about the line y = x = z by a given angle. This involves creating new variables (t, u and v) that represent the rotation matrix multiplied by the input x, y and z values.
The coordinate input would take the form of (p,q,s)=(x,y,z) and the angle of rotation is labelled as 'alpha'.
The code:
function [t,u,v] = rotation(p,q,s,alpha)
t = p((1-cosd(alpha))/3 + cosd(alpha)) + q(((1-cosd(alpha))/3 - sind(alpha)/sqrt(3))) + s((1-cosd(alpha)/3)+(sind(alpha)/sqrt(3)));
u = p((1-cosd(alpha)/3)+(sind(alpha)/sqrt(3))) + q((1-cosd(alpha)+cosd(alpha))/3) + s(((1-cosd(alpha))/3 - sind(alpha)/sqrt(3)));
v = p(((1-cosd(alpha))/3 - sind(alpha)/sqrt(3))) + q((1-cosd(alpha)/3)+(sind(alpha)/sqrt(3))) + s((1-cosd(alpha)+cos(alpha))/3);
end
I had hoped that when using the function in the command window, such as
>> rotation(24,31,62,60)
  • Where the coordinate is (24,31,62) and the angle = 60
Would output the rotated coordinates, in the form [t,u,v].
However, these two errors keep returning and I'm not sure what went wrong:
Array indices must be positive integers or logical values.
Error in rotation (line 2)
t = p((1-cosd(alpha))/3 + cosd(alpha)) + q(((1-cosd(alpha))/3 – sind(alpha)/sqrt(3))) +
s((1-cosd(alpha)/3)+(sind(alpha)/sqrt(3)));
I know the second error is likely a syntax mistake of mine, but I can't spot it, and the first error is new to me.
Please help!
Thanks and apologies if this is a simple fix. I'm still learning 🙂

Best Answer

You may have missed all the multiplication signs, such as:
t = p*((1-cosd(alpha))/3 + cosd(alpha)) + q*(((1-cosd(alpha))/3 - sind(alpha)/sqrt(3))) + s*((1-cosd(alpha)/3)+(sind(alpha)/sqrt(3)));
Matlab will treat pqs as a matrix if you use () directly after them, but the content in the parentheses is not an integer and cannot be indexed, so an error is raised.
by the way, the third formula should be wrong, because you use the sin function instead of sind. Please recheck the correctness of the formula used in this program.