Hello, how do I display the equation for a polyfit line on this plot?

조회 수: 639 (최근 30일)
if true
% code
end
p = polyfit(x,y,1);
d = polyval(p,x);
plot(x,d,'k--')
where x and y are columns of 9, averaged from 3 original sets of 9 data point columns each.
  댓글 수: 6
Steven Lord
Steven Lord 2021년 6월 2일
One tweak is that you can include + in the format specifier itself to avoid "+ -<number>" while displaying the sign. Look at the linear term in txt1 and txt2.
a = 2;
b = -pi;
c = exp(1);
txt1 = sprintf('y = %.4f*x^2 +%.4f*x +%.4f', a, b, c)
txt1 = 'y = 2.0000*x^2 +-3.1416*x +2.7183'
txt2 = sprintf('y = %.4f*x^2 %+.4f*x %+.4f', a, b, c)
txt2 = 'y = 2.0000*x^2 -3.1416*x +2.7183'
stephen
stephen 2022년 10월 7일
How would you add this equation into the legend?

댓글을 달려면 로그인하십시오.

채택된 답변

Image Analyst
Image Analyst 2018년 5월 17일
Use text() to display the equation on the graph:
grid on;
% Place equation in upper left of graph.
xl = xlim;
yl = ylim;
xt = 0.05 * (xl(2)-xl(1)) + xl(1)
yt = 0.90 * (yl(2)-yl(1)) + yl(1)
caption = sprintf('y = %f * x + %f', p(1), p(2));
text(xt, yt, caption, 'FontSize', 16, 'Color', 'r', 'FontWeight', 'bold');
  댓글 수: 11
Nadir Bait Saleem
Nadir Bait Saleem 2023년 11월 20일
This system works great, thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

the cyclist
the cyclist 2018년 5월 17일
편집: the cyclist 2018년 5월 17일

Here is an example of how you can do this.

There are more efficient ways (e.g. using polyval on both the min and max at the same time), but I thought this might be clearer.

rng default
N = 10;
x = randn(N,1);
y = x + 0.3*randn(N,1);
p = polyfit(x,y,1);
x_min = min(x);
x_max = max(x);
d_min = polyval(p,x_min);
d_max = polyval(p,x_max);
figure
hold on
scatter(x,y)
plot([x_min x_max],[d_min d_max],'k--')
  댓글 수: 3
the cyclist
the cyclist 2018년 5월 17일
Ah, I misunderstood the question. I thought you wanted to graph the equation, and it was not working.
Charles Naegele
Charles Naegele 2018년 5월 17일
Thanks for your response anyway.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by