How can I automate the fplot of a polynomial as a function of its degree?

1 回表示 (過去 30 日間)
Andrea Costantino
Andrea Costantino 2022 年 1 月 30 日
コメント済み: Andrea Costantino 2022 年 1 月 31 日
Hi everybody,
I have the following part of a script, in which I plot a polynomial function obtained thorugh a polyfit on measured data.
The script works well, but I was wondering how to automate it as a dunction of the value of g (polynomal degree), without manually changing the f equation.
Thank you very much!
load=[0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0];%measured data
efficiency=[0.274766154 0.567610421 0.700286086 0.766121699 0.831135824 0.848797812...
0.868255235 0.881644769 0.892014 0.898709 0.9018];%measured data
g=5;%polynomial degree
p=polyfit(load,efficiency,g);%coefficient calculation
f=@(x) p(1)*(x)^5+p(2)*(x)^4+p(3)*(x)^3+p(4)*(x)^2+p(5)*(x)+p(6); %polynomial function
figure1=figure('color','w','Position',[1,41,1000,500],'Renderer', 'Painters');
fplot(f,[0 0.9],'linewidth', 1.5,'color',[0.8500, 0.3250, 0.0980]);%plot

採用された回答

KSSV
KSSV 2022 年 1 月 30 日
編集済み: KSSV 2022 年 1 月 30 日
Why you want to use fplot? You can striaght away use polyval.
load=[0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0];%measured data
efficiency=[0.274766154 0.567610421 0.700286086 0.766121699 0.831135824 0.848797812...
0.868255235 0.881644769 0.892014 0.898709 0.9018];%measured data
g=5;%polynomial degree
p=polyfit(load,efficiency,g);%coefficient calculation
x = linspace(0,0.9,20) ;
y = polyval(p,x,'*r') ;
f=@(x) p(1)*(x)^5+p(2)*(x)^4+p(3)*(x)^3+p(4)*(x)^2+p(5)*(x)+p(6); %polynomial function
figure1=figure('color','w','Position',[1,41,1000,500],'Renderer', 'Painters');
fplot(f,[0 0.9],'linewidth', 1.5,'color',[0.8500, 0.3250, 0.0980]);%plot
Warning: Function behaves unexpectedly on array inputs. To improve performance, properly vectorize your function to return an output with the same size and shape as the input arguments.
hold on
plot(x,y,'sb')
If you are supposed to use polynomial then you can achieve that using poly2sym. Read about this function.
  1 件のコメント
Andrea Costantino
Andrea Costantino 2022 年 1 月 31 日
Definitively better with polyval . Thank you so much!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangePolynomials についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by