MATLAB: How to do a “best fit polynomial of degree 2” for the graph

bestfitlinelinear regressionplot

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

Best Answer

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')
Related Question