Function stuck in a 'while loop'

2 views (last 30 days)
Jackie
Jackie on 23 Jul 2013
I have a function to find the coefficients of a polynomial correlation between 3 data sets. The code has 6 simultaneous equations in matrix form to calculate the 6 coefficients (using least squares regression) and then uses a while loop to reduce the rmse (root mean squared error) to a minimum while updates the coefficients therefore validating the results.
The code is this:
function F = matrices; %Name to call the function from the command window
X = [259, 266, 298, 322, 310, 339, 398]; %These need to be
Y = [64.6, 65.48, 65.28, 65.66, 65.86, 65.83, 65.37]; %adjusted according
Z = [-42, -35.8, -24.8, -16, -19.7, -9.5 -1]; %to the correlation.
X2 = X .* X; %Used to simplify the matrix notation within
X3 = X2 .* X; %the while loop.
Y2 = Y .* Y;
Y3 = Y2 .* Y;
Z2 = Z .* Z;
n = 7; %Number of data points.
RMSE = 1; %Initial RMSE guess to use in equation on line 28
A = 1; %Initial coefficient guesses, need to make sure
B = 1; %that the initial guesses don't have an effect on
C = 1; %the final answer.
D = 1;
E = 1;
F = 1;
while RMSE>0.01 %While loop to keep recalculating the root mean
%squared error if it is larger than the tolerance,
%or minimum value set previously.
m = A.*X2 + B.*X + C.*Y2 + D.*Y + E.*Y.*X + F;
%The assumed form of the correlation equation.
RMSE = ((sum(((m-Z).^2).*(1:7)))/7).^(0.5);
%RMSE calculation used to create most valid
%correlation.
%Enter the least squares code to update the variables, A B C D E F?
q = [X3 .* 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, Y2, X .* Y2, Y;
X3 .* Y, X2 .* Y, Y3 .* X, X .* Y2, X2 .* Y2, Y .* X;
X2, X, Y2, Y, Y .* X, ones(1,length(X))];
p = [X2.*Z, X.*Z, Y2.*Z, Y.*Z, Y.*Z, Z2];
x=q/p;
x(1) = 'A'
x(2) = 'B' %Necessary to update the coefficient values,
x(3) = 'C' %without these commands the x matrix is returned
x(4) = 'D' %exactly the same every time.
x(5) = 'E'
x(6) = 'F'
end %To end the while loop.
A %To recall each of the calculated coefficients and the final
B %root mean squared error value showing the validity of the
C %corelation.
D
E
F
RMSE %A value closer to 0 is better.
end
This will create the 6 coefficients and keep updating them without getting to a point where the rmse is low enough. Any ideas or suggestions would be appreciated.
Thanks
P.S. my company's version of matlab doesnt have a curve fitting toolbox which would solve all my problems, hence the long winded approach!

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!