Filter löschen
Filter löschen

Add equations to my polynomial fit on the graph

68 Ansichten (letzte 30 Tage)
Chalisa Mawla
Chalisa Mawla am 18 Jul. 2022
Beantwortet: Star Strider am 18 Jul. 2022
%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')

Antworten (2)

Torsten
Torsten am 18 Jul. 2022
Bearbeitet: Torsten am 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))])
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 am 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
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!
.

Kategorien

Mehr zu 2-D and 3-D Plots finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by