Clear Filters
Clear Filters

Undefined function or variable 'y'.

2 views (last 30 days)
Leandro  Cavalheiro
Leandro Cavalheiro on 23 Oct 2016
Commented: Steven Lord on 23 Oct 2016
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.

Answers (1)

Steven Lord
Steven Lord on 23 Oct 2016
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 Comments
Leandro  Cavalheiro
Leandro Cavalheiro on 23 Oct 2016
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 on 23 Oct 2016
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.

Sign in to comment.

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!