Polyfit and polyval plot intercepting zero

260 views (last 30 days)
Hi Folks
I have a question about the polynomial regression function polyfit. Lets say that we have two random vector, for example; a = [2.1484, 2.1118, 2.0759, 2.0550, 2.0106]; b = [20.530, 20.221, 19.972, 19.721, 19.693];
If we want to do a polynomial regression it is very easily done by the inbuilt function: p = polyfit(a,b,n) If I want to plot the points and the polynomial curve it is also very easily done by the polyval function;
p = polyfit(p,a,n); q = polyval(p,q); plot(a,b,'r',a,q,'b')
(I think this is the right code, this first part illustrates the points in read and the second part the polyval function in blue) But I FOUND IT VERY HARD to make an polynomial regression which is forced to intercept the zero (this is in contrary pretty easy in excel). How can I achieve the polynomial evaluation, polyval, for an curve that intercept zero and easily put the function in a plot command with the points from vector a and b above? By the way, if it is possible, would it be possible to also combine all this, dots from a and b vectors, the polynomial through zero in a plot for standard deviation (the errorbar(a,b) function) and plot standard deviations for all the points from a and b.
Would really appreciate answer, have a nice day, regards from Sweden

Answers (2)

Torsten
Torsten on 19 Feb 2015

math man
math man on 18 Dec 2018
Another, more vulgar way to solve this is to simply force where you want your Origin to be (Y at 0):
Where your varargin is a set of forced input pairs such as [0,0].
function [XY,Fit] = XY_ForceAndFitPoly(XY,PolyParamCount,varargin)
ForcedPairsRow = cell2mat(varargin);
ForcedPairsCount = size(ForcedPairsRow,2)/2;
for pair = 1:ForcedPairsCount
ForcedPair = ForcedPairsRow(1,1+(pair-1)*2:2+(pair-1)*2);
ForcedBlock = repmat(ForcedPair,10000,1);
XY = vertcat(XY,ForcedBlock);
end
Fit = polyfit(XY(:,1),XY(:,2),PolyParamCount);
XPlotVals = linspace(-.2,.2,31);
FitVals = polyval(Fit,XPlotVals);
hold on;
plot(XPlotVals,FitVals,'bo')
end

Categories

Find more on Polynomials in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!