6. Functions : Stat Library Functions : LSQ Function : Example—LSQ function:
 
Share this page                  
Example—LSQ function:
/*  Given x-axis values 0,1,2,3,4,5 and y-axis values
**  0,2,6,12,20,30 as data points calculate slope,
**  intercept, and correlation coefficient for the
**  linear equation that best fits these data points
*/
initialize =
declare
x = array of FloatObject;
y = array of FloatObject;
status = Integer;
m = Float;    /* slope */
c = Float;    /* intercept */
co = Float;   /* correlation */
j = integer not null;
begin
for j = 1 to 6 do
x[j].value = j - 1;
y[j].value = j - 1 + (j - 1)**2;
endfor;
end
on click btn_calc =
begin
status = lsq(xData = x, yData = y,
slope = byref(m),
intercept = byref(c),
correlation = byref(co));
if status = ER_OK then
msgbuf = 'slope = ' + text(m) + HC_NEWLINE + 'intercept = ' +
text(c) + HC_NEWLINE + 'correlation = ' + text(co);
message msgbuf;
else
message 'error calculating lsq';
endif;
end
The resulting equation from the values returned from LQS in this example is y = 6x - 3.333 with a correlation of .972. This is shown in the following graph of the data points and the linear equation: