How do I do a "best fit polynomial of degree 2" for my graph?
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Nathen Eberhardt
el 16 de Abr. de 2020
Comentada: John D'Errico
el 16 de Abr. de 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
Respuesta aceptada
John D'Errico
el 16 de Abr. de 2020
Editada: John D'Errico
el 16 de Abr. de 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 comentarios
John D'Errico
el 16 de Abr. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Polynomials en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!