Add equations to my polynomial fit on the graph

조회 수: 27 (최근 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 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