Line of Best Fit

조회 수: 14 (최근 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 CenterFile Exchange에서 Surface and Mesh Plots에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by