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

7 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

John D'Errico
John D'Errico il 16 Apr 2020
Modificato: John D'Errico il 16 Apr 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 Commenti
Nathen Eberhardt
Nathen Eberhardt il 16 Apr 2020
Ohhhh I see now, Thank you for the help and feedback!
John D'Errico
John D'Errico il 16 Apr 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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Polynomials in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by