フィルターのクリア

Undefined function or variable 'y'.

2 ビュー (過去 30 日間)
Leandro  Cavalheiro
Leandro Cavalheiro 2016 年 10 月 23 日
コメント済み: Steven Lord 2016 年 10 月 23 日
I'm trying to compute sin(x) with the nth order of the Taylor Series around a = 0; The function is
function [y] = TaylorSeries(n,x)
for i = 0:n
y = y + ((-1)^i * x^(2*i + 1))/(factorial(2*i + 1));
end
end
I'm getting -> Undefined function or variable 'y'.
Error in TaylorSeries (line 4) y = y + ((-1)^i * x^(2*i + 1))/(factorial(2*i + 1));
What's wrong? I can't seem to get on well with Matlab.

回答 (1 件)

Steven Lord
Steven Lord 2016 年 10 月 23 日
You're trying to use the value of the variable y on the line of code inside your for loop, but you haven't yet defined that variable. Because of this MATLAB doesn't know what value you want to use, and so it complains by throwing an error. Add this line before your loop to define/initialize that variable. That way MATLAB knows to use the value y = 0 on the first iteration of the loop.
y = 0;
  2 件のコメント
Leandro  Cavalheiro
Leandro Cavalheiro 2016 年 10 月 23 日
I'd tried it before and got this:
>> TaylorSeries(7,pi/2)
g =
0
k =
1
Output argument "y" (and maybe others) not assigned during call to "factorial".
Error in TaylorSeries (line 5)
y = y + ((-1)^i * x^(2*i + 1))/(factorial(2*i + 1));
Steven Lord
Steven Lord 2016 年 10 月 23 日
That suggests that you've written your own factorial function (rather than use the factorial function included in MATLAB) but that there is at least one code path through it that doesn't define the output argument. My suspicion is that when you call factorial(1) it doesn't assign a value to the output.
If your homework assignment (I'm assuming this is part of a homework assignment) permits it, I recommend using the factorial function in MATLAB rather than writing your own.

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

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by