Undefined function or variable 'y'.

2 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by