Hello, how do I display the equation for a polyfit line on this plot?
Mostra commenti meno recenti
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 Commenti
Cole Schoonover
il 7 Feb 2020
Are you able to set the number of sigfigs that show for the m and b in mx+b
Image Analyst
il 7 Feb 2020
Cole, what is a "sigfig"? I've never heard of it.
Elise Atchison
il 22 Mag 2020
significant figures
Image Analyst
il 22 Mag 2020
Cole, you can set the number in the format string in sprintf() when you go to create the string. For example, to have 4 digits to the right of the decimal point, use %.4f:
txt = sprintf('y = %.4f * x + %.4f', m, b);
text(30, 0.5, txt, 'Color', 'r', 'FontSize', 15, 'FontWeight', 'Bold', 'HorizontalAlignment', 'left');
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)
txt2 = sprintf('y = %.4f*x^2 %+.4f*x %+.4f', a, b, c)
stephen
il 7 Ott 2022
How would you add this equation into the legend?
Risposta accettata
Più risposte (1)
the cyclist
il 17 Mag 2018
Modificato: the cyclist
il 17 Mag 2018
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 Commenti
Charles Naegele
il 17 Mag 2018
the cyclist
il 17 Mag 2018
Ah, I misunderstood the question. I thought you wanted to graph the equation, and it was not working.
Charles Naegele
il 17 Mag 2018
Categorie
Scopri di più su Elementary Math in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

