Add equations to my polynomial fit on the graph
27 views (last 30 days)
Show older comments
%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 Comments
Answers (2)
Torsten
on 18 Jul 2022
Edited: Torsten
on 18 Jul 2022
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 Comments
Star Strider
on 18 Jul 2022
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 Comments
See Also
Categories
Find more on Surface and Mesh Plots in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!