Line of Best Fit

15 visualizaciones (últimos 30 días)
Dominique Davis
Dominique Davis el 4 de Nov. de 2019
Respondida: Image Analyst el 5 de Nov. de 2019
Trying to get a line of best fit through my points.
Here is an example of my scatter plot:
x = [1 2 3 4]
z = [rate1 rate2 rate3 rate4]
scatter(x, z)
Below is what I am trying for the line of best fit but am getting an error:
fit = polyfit(x, y, 1);
fittedX = linspace(min(x), max(x), 100);
fittedZ = polyval(fit, fittedX);
hold on;
plot(fittedX, fittedZ, 'r-', 'LineWidth', 3);
  3 comentarios
dpb
dpb el 5 de Nov. de 2019
fittedX = linspace(min(x), max(x), 100);
fittedZ = polyval(fit, fittedX);
NB: It takes only the two points to define the line to plot between [min(x) max(x)]; the other 98 are superfluous above.
Richard Brown
Richard Brown el 5 de Nov. de 2019
Assuming you mean z instead of y, this code should work, assuming rate1, rate2, etc are scalars.

Iniciar sesión para comentar.

Respuestas (1)

Image Analyst
Image Analyst el 5 de Nov. de 2019
Do you have an extra y floating around? Maybe try
clear all;
to get rid of it. You're calling
fit = polyfit(x, y, 1);
instead of
fit = polyfit(x, z, 1);
If it even works, it's because there is a y variable hanging around, perhaps from some other code you ran or maybe from before you renamed variables.
Like John said, you forgot to tell us a critical point : what the actual error was. If it says something like it doesn't know what y is (y is undefined), then you probably just forgot to pass z (instead of y) into polyfit. If you use z, it should work, like Richard said.

Categorías

Más información sobre Surface and Mesh Plots en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by