Effacer les filtres
Effacer les filtres

How do I do a "best fit polynomial of degree 2" for my graph?

16 vues (au cours des 30 derniers jours)
Nathen Eberhardt
Nathen Eberhardt le 16 Avr 2020
Commenté : John D'Errico le 16 Avr 2020
Heres my code:
clc,clear,close all ,format compact
%Load NoisyWave into script
load('NoisyWave.csv')
%Use readmatrix to convert the csv to matlab data
readmatrix('NoisyWave.csv');
%Seperating the two rows of data
A = NoisyWave(1,:);
B = NoisyWave(2,:);
%scatter plot
figure(1)
hold on
scatter(A,B)
%Best fit line
P = polyfit(A, B, 2);
Bestfit = polyval(P, A);
plot(A, Bestfit, '-r')
This Is a picture of my graph, Is this normal? I think It should be only one line but mine does way more than one line. Any help is appreciated
  1 commentaire
Nathen Eberhardt
Nathen Eberhardt le 16 Avr 2020
sorry my photo should be at the bottom of the script

Connectez-vous pour commenter.

Réponse acceptée

John D'Errico
John D'Errico le 16 Avr 2020
Modifié(e) : John D'Errico le 16 Avr 2020
You did the fit correctly. What was wrong was in the very last line, where you plotted the result.
Your data is not sorted, but then you used plot to plot the data, connecting the points with a LINE! You did connect the dots, on data that is essentially random.
Had you used sort, to sort the data for increasoing x, and then re-arranged y in the same order, then you would have gotten the same resulting coefficients, but the plot would have looked very pretty. Or, you could have just plotted the curve as:
plot(A, Bestfit, '.r')
There the plot will be done, but the points will not be connected with lines between them.
x = rand(100,1);
y = sin(pi*x) + randn(size(x))/10;
p2 = polyfit(x,y,2);
plot(x,y,'o',x,polyval(p2,x),'r-')
figure
plot(x,y,'r.',x,polyval(p2,x),'go')
  2 commentaires
Nathen Eberhardt
Nathen Eberhardt le 16 Avr 2020
Ohhhh I see now, Thank you for the help and feedback!
John D'Errico
John D'Errico le 16 Avr 2020
I make the same mistake myself sometimes, forgetting that my data was unsorted. When you see exactly this type of plot, you will now remember what caused it.

Connectez-vous pour commenter.

Plus de réponses (0)

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