Advertisement
Guest User

Linear Regression

a guest
Apr 9th, 2020
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.83 KB | None | 0 0
  1. clear all
  2. clc
  3.  
  4. X=[1 2 3 4 5 6 7 8 9 10] %array X
  5. Y=[12 14 24 28 19 28 30 37 41 45] %array Y
  6.  
  7. scatter(X,Y) %to obtain scatter plot
  8.  
  9. %for axis labels
  10. xlabel('X')
  11. ylabel('Y')
  12.  
  13. %to obtain line of best fit
  14. f=polyfit(X,Y,1);
  15. v=polyval(f,X);
  16. hold on
  17. grid on;
  18. plot(X,v)
  19.  
  20. %calculation of estimates b0 and b1
  21. AvgX=mean(X); %mean value of array X
  22. AvgY=mean(Y); %mean value of array Y
  23.  
  24. n=length(X); %setting n to 10(number of entries in arrays)
  25. sum1=sum(X.*Y); %summation of Xi*Yi
  26. sum2=sum(X); %summation of Xi
  27. sum3=sum(Y); %summation of Yi
  28. sum4=sum(X.^2); %summation of Xi^2
  29. sum5=sum2^2; %squaring the summation of Xi
  30.  
  31. b1=(((n*sum1)-(sum2*sum3))/((n*sum4)-sum5)); %to obtain value of b1
  32. b0=AvgY-(b1*AvgX); %to obtain value of b0
  33.  
  34. disp("Equation of line of best fit is: Y = "+b0+" + "+b1+"X") %to display equation
  35. disp(" ")%empty line in command window
  36.  
  37. %computing R^2 coefficient
  38. sum6=sum((X-AvgX).*(Y-AvgY)); %summation of (Xi-AvgX)(Yi-AvgY)
  39. sum7=sum((X-AvgX).^2); %summation of (Xi-Avg(X))^2
  40. sum8=sum((Y-AvgY).^2); %summation of (Yi-Avg(Y))^2
  41.  
  42. rsqrdcoeff = ((sum6)/(sqrt(sum7*sum8)))^2; %to obtain value of R^2 coefficient
  43. disp("R^2 Coefficient = "+rsqrdcoeff) %to display r^2 coefficient
  44. disp(" ") %empty line in command window
  45.  
  46. %to calculate length of unstandardised residuals
  47. for k=1:length(X)
  48.     residualss(k)=(((-b1)*X(k))+(Y(k))-b0)/(sqrt((b1^2)+(1^2)));
  49. end
  50.  
  51. LengthOfResiduals = abs(residualss') %to display absolute value of lengths in a vector
  52.  
  53. %to plot unstandardised residuals
  54. GradientOfResiduals=-1/(b1) %to obtain gradient of residuals
  55.  
  56. %loop to obtain y-intercepts of residuals
  57. c=zeros(1,10);
  58. for i=1:10
  59.     c(i)=Y(i)-(GradientOfResiduals*X(i));
  60.     xInt=(c(i)- b0)/(b1-GradientOfResiduals);
  61.     yInt=(GradientOfResiduals*xInt)+c(i);
  62.    
  63.     line([X(i) xInt],[Y(i) yInt], 'Color', 'b');
  64. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement