I am trying to fit the polynomials to the data with 0,1,2 degrees respectively and plot them on the same graph. I wonder why there is only one line shown on the plot which is the 0 degree polynomial.
y = flip(AdjClose).'
x = 1:503;
polyfit(y,x,0);
coef1 = polyfit(y,x,0);
y1 = polyval(coef1,x);
hold on
plot(x,y);
plot(x,y1);
polyfit(y,x,1);
coef2 = polyfit(y,x,1);
y2 = polyval(coef2,x);
plot(x,y2);
polyfit(y,x,2);
coef3 = polyfit(y,x,2);
y3 = polyval(coef3,x);
plot(x,y3);

 採用された回答

the cyclist
the cyclist 2016 年 2 月 16 日

3 投票

Because the syntax should be

polyfit(x,y,N)

and not

polyfit(y,x,N)

Here is some code that illustrates the fix:

x = 1:503;
y = 250 + 0.02*x + 0.005*x.^2 + 0.2*rand(1,503).*x;
figure
polyfit(y,x,0);
coef1 = polyfit(x,y,0);
y1 = polyval(coef1,x);
hold on
plot(x,y,'.');
plot(x,y1);  
polyfit(x,y,1);
coef2 = polyfit(x,y,1);
y2 = polyval(coef2,x);
plot(x,y2);
polyfit(y,x,2);
coef3 = polyfit(x,y,2);
y3 = polyval(coef3,x);
plot(x,y3);

5 件のコメント

Jovos
Jovos 2016 年 2 月 16 日
編集済み: the cyclist 2016 年 2 月 16 日
After I changed the code to the following, there still is not graph showing. Can you tell me where is wrong?
y = flip(AdjClose).'
x = 1:503;
polyfit(x,y,0);
coef1 = polyfit(x,y,0);
y1 = polyval(coef1,x);
hold on
plot(x,y);
plot(x,y1);
polyfit(x,y,1);
coef2 = polyfit(x,y,1);
y2 = polyval(coef2,x);
plot(x,y2);
polyfit(x,y,2);
coef3 = polyfit(x,y,2);
y3 = polyval(coef3,x);
plot(x,y3);
the cyclist
the cyclist 2016 年 2 月 16 日
It's difficult to know the problem without being able to run your code. Can you post a *.mat file with the value of AdjClose?
Jovos
Jovos 2016 年 2 月 17 日
Here it is.
the cyclist
the cyclist 2016 年 2 月 17 日
It's because your last y value is NaN, which is causing the fitted coefficients to all be NaN, and therefore unplottable.
Put the lines
x(end) = [];
y(end) = [];
in your code before the first fit, and you will see results.
Jovos
Jovos 2016 年 2 月 18 日
Very nice!

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2016 年 2 月 17 日

0 投票

When you use "hold on" before you have done any plotting, your xlim and ylim are frozen at their default values, which are [0 1] and [0 1]. If your plotting goes outside that range then nothing will show up. You should delay the "hold on" until after the first plot is done.

1 件のコメント

Jovos
Jovos 2016 年 2 月 17 日
I don't think that makes a change.

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2016 年 2 月 16 日

コメント済み:

2016 年 2 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by