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);
%-------------------------------------------------------
1 comment:
Thanks!!!!... but using other values, the ecuation not apear, for example:
x=[15 15 63 49 58 31 7 68 73 67 72 56 62 62 78 51 38 29 52 9 19 88 99 89 94 66 66 65 67 67 59 62];
y=[2 1.99 2.06 2.03 2.06 2.02 1.97 2.08 2.1 2.08 2.09 2.06 2.06 2.07 2.09 2.04 2.01 2 2.05 1.98 2.02 2.12 2.14 2.13 2.1 2.07 2.07 2.07 2.07 2.07 2.06 2.06];
Post a Comment