Line of Best Fit

15 Ansichten (letzte 30 Tage)
Dominique Davis
Dominique Davis am 4 Nov. 2019
Beantwortet: Image Analyst am 5 Nov. 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 Kommentare
dpb
dpb am 5 Nov. 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 am 5 Nov. 2019
Assuming you mean z instead of y, this code should work, assuming rate1, rate2, etc are scalars.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Image Analyst
Image Analyst am 5 Nov. 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.

Community Treasure Hunt

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

Start Hunting!

Translated by