Matlab Code for Linear Regression and R Square in MATLAB


%Here, sample code for linear regression and R square calculation

close all

clear all

%---------- generate x-data and y-data ---------

x=[1,1.2,1.53,1.64,2.15,2.36];

y=[151.4,142.9,135.3,116.42,91.9,70.8];

%----------- Linear regression -----------------

p= polyfit(x,y,1);

f= polyval(p,x);

%----------- Call R-square function ------------

r2=Rsquare(x,y,p);





%------------- Plot data -----------------------

figure()

plot(x,y,'*k');hold on

plot(x,f,'-r'); % show linear fit

xlabel('index');

ylabel('Intensity a.u.');

title('Test: Linear regreesion && R-square');

%------- Show y-data on current figure ---------

[row col]=size(y);

for i=1:col

str=num2str(y(i));

text(x(i),y(i),str,'Color',[0 0 1]);

end

%--Show linear equation on current figure -------

m1=num2str(p(1));c1=num2str(p(2));Rsquare1=num2str(r2(1));

text(1.05,80,['y= ',m1,'x+',c1,' , R^2= ',Rsquare1,'.'],'FontSize',10,'FontName','Times New Roman');



save source code in function file



%---------The function return R-square value -------------

%--------- input data ==> x-data, y-data and p-data ----

%--------- output data ==> r2

function [r2]=Rsquare(x,y,p)



Ymeasure=y;

Ycalculate=(p(1)*x)+p(2);

meanY=mean(Ymeasure);

deltaY2=sum((Ycalculate-Ymeasure).^2);

distanceY2=sum((Ymeasure-meanY).^2);

r2=1-(deltaY2/distanceY2);


Contact:
Mr. Roshan P. Helonde
Mobile: +91-7276355704
WhatsApp: +91-7276355704
Email: roshanphelonde@rediffmail.com
Share:

Total Pageviews

CONTACT US

Prof. Roshan P. Helonde
Mobile: +917276355704
WhatsApp: +917276355704
Email: roshanphelonde@rediffmail.com

Enter Project Title

Popular Projects

All Archive

Contact Form

Name

Email *

Message *