Polyfit and polyval plot intercepting zero

246 vues (au cours des 30 derniers jours)
Johan  Lilliestråle
Johan Lilliestråle le 19 Fév 2015
Commenté : TEDDY OKOLO le 20 Août 2021
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

Réponses (2)

Torsten
Torsten le 19 Fév 2015
  2 commentaires
TheLast One
TheLast One le 2 Juin 2019
Thanks!
TEDDY OKOLO
TEDDY OKOLO le 20 Août 2021
Thanks! This was extremely helpful.

Connectez-vous pour commenter.


math man
math man le 18 Déc 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

Catégories

En savoir plus sur Polynomials dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by