Line of Best Fit
15 views (last 30 days)
Show older comments
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 Comments
dpb
on 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
on 5 Nov 2019
Assuming you mean z instead of y, this code should work, assuming rate1, rate2, etc are scalars.
Answers (1)
Image Analyst
on 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.
0 Comments
See Also
Categories
Find more on Surface and Mesh Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!