how to make something between quotation automatic!

I want to make 'poly2' automatic by changing n? How can I do this using for example eval function?
n=2;% 3,4,....
f1 = fit(x,y,'poly2')

 採用された回答

Steven Lord
Steven Lord 2022 年 8 月 16 日

0 投票

If you're just fitting polynomials you could use polyfit and polyval, specifying n as the third input argument.
load census
n = 2;
[p, s] = polyfit(cdate, pop, n);
plot(cdate, pop, 'o', cdate, polyval(p, cdate, s), '-')
But you can also use fit if you want. There's no need to use eval here, just use string + or char manipulation.
theFit = fit(cdate, pop, "poly" + n, 'Normalize', 'on') % or
theFit =
Linear model Poly2: theFit(x) = p1*x^2 + p2*x + p3 where x is normalized by mean 1890 and std 62.05 Coefficients (with 95% confidence bounds): p1 = 25.18 (23.58, 26.79) p2 = 75.43 (74.04, 76.83) p3 = 61.74 (59.7, 63.79)
theFit2 = fit(cdate, pop, ['poly', num2str(n)], 'Normalize', 'on') % or
theFit2 =
Linear model Poly2: theFit2(x) = p1*x^2 + p2*x + p3 where x is normalized by mean 1890 and std 62.05 Coefficients (with 95% confidence bounds): p1 = 25.18 (23.58, 26.79) p2 = 75.43 (74.04, 76.83) p3 = 61.74 (59.7, 63.79)
theFit2 = fit(cdate, pop, sprintf('poly%d', n), 'Normalize', 'on')
theFit2 =
Linear model Poly2: theFit2(x) = p1*x^2 + p2*x + p3 where x is normalized by mean 1890 and std 62.05 Coefficients (with 95% confidence bounds): p1 = 25.18 (23.58, 26.79) p2 = 75.43 (74.04, 76.83) p3 = 61.74 (59.7, 63.79)
figure
plot(cdate, pop, 'o')
hold on
plot(theFit, '-')

1 件のコメント

Ham Man
Ham Man 2022 年 8 月 16 日
Steven thank you so much for nice explanation with many choices. Much appreciated!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLinear and Nonlinear Regression についてさらに検索

質問済み:

2022 年 8 月 16 日

コメント済み:

2022 年 8 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by