% Simple pseudocode for calculating the first-order least-square fit of y vs x, % including the Slope and Intercept and the predicted standard deviation of % the slope (SDslope) and intercept (SDintercept). % Uses only the length function and sqrt (square root) functions % % Assumptions: The data are in the arrays x and y; % length(x) returns the nunber of points; % x(i) is the ith element of array x, where i is integer; % x^2 is the square of x, etc. % The for loops (for i=1:n....end) increment i in unit steps. n=length(x) sumx=0 sumy=0 sumxy=0 sumx2=0 for i=1:n sumx=sumx+x(i) sumy=sumy+y(i) sumxy=sumxy+x(i)*y(i) sumx2=sumx2+x(i)*x(i) end meanx=sumx/n meany=sumy/n slope=(n*sumxy-sumx*sumy)/(n*sumx2-sumx*sumx) intercept=meany-(slope*meanx) ssy=0 ssr=0 ssx=0 for i=1:n ssy=ssy+(y(i)-meany)^2 ssr=ssr+(y(i)-intercept-slope*x(i))^2 ssx=ssx+(x-meanx).^2 end R2 = 1-(ssr/ssy) SDslope = sumy/sqrt(sxx) SDintercept = sumy*sqrt(1/(n-(sumx^2)/sumx2))