How to create a string that depends on user input variables?

2 ビュー (過去 30 日間)
Joseph Wales
Joseph Wales 2018 年 4 月 28 日
コメント済み: Rik 2021 年 3 月 1 日
Hi,
I am currently writing a script in which data collected from a separate file is used to plot curve fits.
I also need to include the equation used for the curve fit on the plot.
I encountered an issue when attempting to do this with a general polynomial, as the degree of the polynomial is decided by the user.
A shortened version of my code is this:
data = load('data_1.txt');
x = data(:,1);
y = data(:,2);
d = input('To what degree would you like your polynomial?');
p = polyfit(x,y,d);
yfit = polyval(p,x);
plot(x,y,'bo',x,yfit,'r--')
I need a way to create a string that is the correct form of the equation of the polynomial so that it can be properly displayed on the plot.
For example, if the user chooses degree 2, I need to display the equation "p(1)*x^2 + p(2)*x + p(3)" on the plot.
Is there a way to do this for any value of degree?
Any help is appreciated, thanks.

回答 (2 件)

Rik
Rik 2021 年 2 月 28 日
You can create this text with sprintf and some minor tweaks:
str=sprintf('p(%d)*x^%d +', [1:d;(d-1):-1:0]);
str=strrep(str,'^1','');
str=strrep(str,'x^0 + ','');

Siyu Guo
Siyu Guo 2018 年 4 月 28 日
Try poly2str function. For example, s = poly2str(p, 'x').
  1 件のコメント
培林 王
培林 王 2021 年 2 月 28 日
Well, I can't use this function now and I didn't find it in the toolbx. what's the problem?

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

カテゴリ

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