MATLAB: Polyfit returns the wrong correlation coeffcient when I try do a linear regression

correlation coefficientlinear regressionpolyfitpolyvalregression

Hello 🙂
I am trying to do a linear regression for a set of data, but the regression coefficient returned by matlab polyfit don't fit my data.
The data is plot just fine but the linear regression function seems very odd…
Please see the attached figure
I tried to plot with polyval (option 1) and with a linear relation (y=ax+b) (option 2) but it does not make any difference… The regression coefficient returned are just no the good ones…
Can anyone help me?
subwFMA = w10MeanFMA(521:771, 41:161); %sub mean wind speed
subssrdFMA = ssrdMeanFMA(521:771, 41:161); %sub mean solar radiation
%OPTION 1
pFMA = polyfit(subwFMA(:),subssrdFMA(:),1); %find regression coefficient a and b for a linear regression
fFMA = polyval(pFMA,subwFMA(:)); %linear regression function

figure(1)
plot(subwFMA(:),subssrdFMA(:),'o',subwFMA(:),fFMA,'-');
%OPTION 2
polyfitFMA = polyfit(subwFMA(:),subssrdFMA(:),1); %find correletation coefficient a and b for a linear regression
aFMA = polyfitFMA(1,1); %coeff a
bFMA = polyfitFMA(1,2); %coeff b
yssrdFMA = aFMA*subwFMA(:) + bFMA; %linear regression function
figure(2)
plot(subwFMA(:),subssrdFMA(:),'o',subwFMA(:),yssrdFMA,'-');
I also tried to reverse my x and y data in polyfit but it makes things even worse!
Thanks

Best Answer

I don't think you are plotting your fitted y values
For example where you have
fFMA = polyval(pFMA,subwFMA(:)); %linear regression function

figure(1)
plot(subwFMA(:),subssrdFMA(:),'o',subwFMA(:),yssrdFMA,'-');
I think you want
yssrdfFMA = polyval(pFMA,subwFMA(:)); %linear regression function
figure(1)
plot(subwFMA(:),subssrdFMA(:),'o',subwFMA(:),yssrdFMA,'-');
and where you have
figure(2)
plot(subwFMA(:),subssrdFMA(:),'o',subwFMA(:),fFMA,'-');
I think you want
figure(2)
plot(subwFMA(:),subssrdFMA(:),'o',subwFMA(:),yssrdFMA,'-');