Add equations to my polynomial fit on the graph

25 ビュー (過去 30 日間)
Chalisa Mawla
Chalisa Mawla 2022 年 7 月 18 日
回答済み: Star Strider 2022 年 7 月 18 日
%I wanted to plot 5 points and make a fit of y=ax^2+bx+c. However, the disp part (in bold) is not working properly. Not only I do not see the equation on my plot, it is not showing on the commands window either.
%Any idea how I might be able to solve this? Thanks a lot!
x=linspace(0.1,0.5,5)
y=[32.2,36.1,42.2,65.67,67.3]
plot(x,y,'.',MarkerSize=15)
hold on
% Fit line to data using polyfit
c = polyfit(x,y,2);
%Display evaluated equation y = m*x + b
disp(['Equation is y = ' num2str(c(1)) '*x^2' + num2str(c(2)) '*x' + num2str(c(3))])
% Evaluate fit equation using polyval
y_est = polyval(c,x);
% Add trend line to plot
hold on
plot(x,y_est,'r--','LineWidth',2)
hold off
xlabel('um')
ylabel('meV', 'Interpreter', 'none')

回答 (2 件)

Torsten
Torsten 2022 年 7 月 18 日
編集済み: Torsten 2022 年 7 月 18 日
x=linspace(0.1,0.5,5);
y=[32.2,36.1,42.2,65.67,67.3];
plot(x,y,'.',MarkerSize=15)
hold on
% Fit line to data using polyfit
c = polyfit(x,y,2);
%Display evaluated equation y = m*x + b
disp(['Equation is y = ' num2str(c(1)) '*x^2 +' num2str(c(2)) '*x +' num2str(c(3))])
Equation is y = 91.6429*x^2 +44.7843*x +25.178
% Evaluate fit equation using polyval
y_est = polyval(c,x);
% Add trend line to plot
hold on
plot(x,y_est,'r--','LineWidth',2)
hold off
xlabel('um')
ylabel('meV', 'Interpreter', 'none')

Star Strider
Star Strider 2022 年 7 月 18 日
It is easier to use fprintf to print to the Command Window. I added a text call uinsg sprintf to demonstrate that option as well.
x=linspace(0.1,0.5,5);
y=[32.2,36.1,42.2,65.67,67.3];
plot(x,y,'.',MarkerSize=15)
hold on
% Fit line to data using polyfit
c = polyfit(x,y,2);
%Display evaluated equation y = m*x + b
% disp(['Equation is y = ' num2str(c(1)) '*x^2' + num2str(c(2)) '*x' + num2str(c(3))])
fprintf('Equation is y = %.3f*x^2 + %.3f*x + %.3f\n',c) % The 'fprintf' Function Is Easier
Equation is y = 91.643*x^2 + 44.784*x + 25.178
% Evaluate fit equation using polyval
y_est = polyval(c,x);
% Add trend line to plot
hold on
plot(x,y_est,'r--','LineWidth',2)
hold off
xlabel('um')
ylabel('meV', 'Interpreter', 'none')
text(0.15, 70, sprintf('y = %.3f*x^2 + %.3f*x + %.3f\n',c)) % ADDED: 'text' & 'sprintf (Optional)
Experiment with this!
.

カテゴリ

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