How do I plot a polynomial equation and set of x-y coordinates on the same graph?

16 次查看(过去 30 天)
I am trying to plot a polynmial and some x-y coordinates on the same graph. I need the coordinates to be visible and the lines to be distingushable from one another (eg. different colors).
Here is the measured data.
coefficients = [0.6252 -0.4165 0.1311 -0.0163 0.0009,-0.0000]
x = [2 5 8 11 14 20];
y = [0.20 0.29 0.44 0.50 0.66 0.56];

采纳的回答

Sam Chak
Sam Chak 2024-5-10
编辑:Sam Chak 2024-5-10
Edit: Your original polynomial coefficients are truncated. So, the polynomial cannot produce an accurate result.
%% data
x = [2 5 8 11 14 20];
y = [0.20 0.29 0.44 0.50 0.66 0.56];
%% polynomial coefficients
coefficients = [0.6252 -0.4165 0.1311 -0.0163 0.0009 -0.0000];
p = fliplr(coefficients)
p = 1x6
0 0.0009 -0.0163 0.1311 -0.4165 0.6252
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
format long
p = polyfit(x, y, numel(x)-1)
p = 1x6
-0.000018175582990 0.000901920438957 -0.016287722908091 0.131052812071305 -0.416499314128809 0.625240054869418
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
%% points generated by polynomial
xx = linspace(x(1), x(end), 181);
yy = polyval(p, xx);
%% plot results
plot(x, y, 'o', 'markersize', 10), hold on
plot(xx, yy), grid on, xlabel('x'), xlabel('y')
legend('data', 'polynomial', 'location', 'northwest')
  9 个评论
Deleted User
Deleted User 2024-5-11
Thank you for that! Sorry to bother you, but I have another question. I’m trying to plot another point on the polynomial. I know the x coordinate is 17.5, but I don’t know the y coordinate. Is there a way I could plot the x coordinate on the polynomial and use the information from the graph to figure out the y coordinate? This coordinate needs to be distinguished from the points (eg. different colour).
Sam Chak
Sam Chak 2024-5-11
编辑:John Kelly 2024-5-20
Hi
You can use the polyval() command in this case.
%% data
x = [2 5 8 11 14 20];
y = [0.20 0.29 0.44 0.50 0.66 0.56];
%% polynomial coefficients
p = polyfit(x, y, numel(x)-1)
p = 1x6
-0.0000 0.0009 -0.0163 0.1311 -0.4165 0.6252
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
%% points generated by polynomial
xx = linspace(x(1), x(end), 181);
yy = polyval(p, xx);
%% find y coordinate with given x coordinate
xpt = 17.5;
ypt = polyval(p, xpt)
ypt = 0.9379
%% plot results
plot(x, y, 'o', 'markersize', 10), hold on
plot(xx, yy), grid on, xlabel('x'), ylabel('y')
plot(xpt, ypt, 'p', 'markersize', 10, 'color', "#7E2F8E"), hold off
legend('data', 'polynomial', 'point', 'location', 'northwest')

请先登录,再进行评论。

更多回答(1 个)

KSSV
KSSV 2024-5-10
x = [2 5 8 11 14 20];
y = [0.20 0.29 0.44 0.50 0.66 0.56];
p = polyfit(x,y,3) ;
yi = polyval(p,x) ;
figure
hold on
plot(x,y,'r')
plot(x,yi,'b')
legend('data points','polynomial fit')

类别

Help CenterFile Exchange 中查找有关 Polynomials 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by