Add equations to my polynomial fit on the graph
68 次查看(过去 30 天)
显示 更早的评论
%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')
0 个评论
回答(2 个)
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))])
% 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')
0 个评论
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
% 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!
.
0 个评论
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!