MATLAB: How to solve a problem where POWER (.^) is required but not recognised by Matlab

elementwise power

I am trying to solve 6 simultaneous equations to obtain coefficients for a correlation between 7 3D points. I have been using the least squares method and have completed most parts by hand. My steps so far have been:
1. Starting out with this correlation equation:
n
sum (a*x_i^2 + b*x_i + c - y_i)^2
i=1
2. Multiplying out the square.
3. Splitting the sum into smaller sums.
4. Taking derivatives with respect to each of the unknowns (A, B, C, D, E, F).
5. Setting each of these equal to zero and then obtaining the matrices to solve for the unknowns.
My function looks like this:
*function M = correlation2;
X = [259 266 298 322 310 339 398];
Y = [64.6 65.48 65.28 65.66 65.86 65.83 65.37];
Z = [-42 -35.8 -24.8 -16 -19.7 -9.5 -1];
q = [X.^4 X.^3 X.^2.*Y.^2 X.^2.*Y X.^3.*Y X.^2;
X.^3 X.^2 X.*Y.^2 Y.*X X.^2.*Y X;
X.^2.*Y.^2 X.*Y.^2 Y.^4 Y.^3 Y.^3.*X Y.^2;
X.^2.*Y X.*Y Y.^3 Y.^3 X.*Y.^2 Y;
X.^3.*Y X.^2.*Y Y.^3.*X X.*Y.^2 X.^2.*Y.^2 Y.*X;
X^2 X Y.^2 Y Y.*X 1];
p = [X.^2.*Z;
X.*Z;
Y.^2.*Z;
Y.*Z;
Y.*Z;
X.^2];
u=q\p
end
And the error message is this:
"Error using ^ Inputs must be a scalar and a square matrix. To compute elementwise POWER, use POWER (.^) instead.
Error in Correlation2 (line 9) q = [X.^4 X.^3 X.^2.*Y.^2 X.^2.*Y X.^3.*Y X.^2;"
Correct me if I am wrong but the notation seems to be correct. Is there any other reason this message would come up?
Thanks in advance!

Best Answer

There is an "X^2" in the last row of q, exactly as the error message says.
Btw, I strongly suggest to add spaces to your code, because Matlab is sure, what e.g.
X.^2.*Y.^2
exactly means, but is the programmer or reader also? Does this mean:
X .^ 2.0 * Y .^ 2
(implicit trailing zero after decimal dot) or
X .^ 2 .* Y .^ 2
Although Matlab accepts a trailing semi-colon as row-separator in matrices, I think the explicit notation is safer:
q = [X .^ 4, X .^ 3, X .^ 2 .* Y .^ 2, X .^ 2 .*Y, X .^ 3 .* Y, X .^ 2; ...
X .^ 3, X .^ 2, X .* Y .^ 2, Y .* X, X .^ 2 .* Y, X;
It happens to often that a semicolon or comma is forgotten and Matlab does not do what the user expects. Then searching the typo can consume a lot of time. An unary minus will be confusing also:
a = 1; b = 2;
q1 = [a -b]
q2 = [a - b]
q3 = [a- b]
q4 = [a-b]
Will all those expressions return the same output? With commas as separators this would be clear immediately.
An another tip: The power operation is expensive, so avoid doing this repeatedly:
X2 = X .* X;
X3 = X2 .* X;
Y2 = Y .* Y;
Y3 = Y2 .* Y;
q = [X4.*X, X3, X2.*Y2, X2.*Y, X3.*Y, X2; ...
X3, X2, X.*Y2, Y.*X, X2.*Y, X; ...
X2.*Y2, X.*Y2, Y3.*Y, Y3, Y3.*X, Y2; ...
X2.*Y, X.*Y, Y3, Y3, X .*Y2, Y; ...
X3.*Y, X2.*Y, Y3.*X, X.*Y2, X2.*Y2, Y.*X; ...
X2, X, Y2, Y, Y .*X, 1];
Here are no numerical constants anymore such that omitting is less risky. I think, this is much easier to read now, e.g. the symmetry is more obvious.