Line of Best Fit

15 ビュー (過去 30 日間)
Dominique Davis
Dominique Davis 2019 年 11 月 4 日
回答済み: Image Analyst 2019 年 11 月 5 日
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 件のコメント
dpb
dpb 2019 年 11 月 5 日
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 2019 年 11 月 5 日
Assuming you mean z instead of y, this code should work, assuming rate1, rate2, etc are scalars.

サインインしてコメントする。

回答 (1 件)

Image Analyst
Image Analyst 2019 年 11 月 5 日
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.

カテゴリ

Help Center および File ExchangeSurface and Mesh Plots についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by