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

조회 수: 7 (최근 30일)
Nathen Eberhardt
Nathen Eberhardt 2020년 4월 16일
댓글: John D'Errico 2020년 4월 16일
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

채택된 답변

John D'Errico
John D'Errico 2020년 4월 16일
편집: John D'Errico 2020년 4월 16일
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
Nathen Eberhardt
Nathen Eberhardt 2020년 4월 16일
Ohhhh I see now, Thank you for the help and feedback!
John D'Errico
John D'Errico 2020년 4월 16일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Polynomials에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by