Undefined function or variable 'y'.
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
0 Kommentare
Antworten (1)
Steven Lord
am 23 Okt. 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 Kommentare
Steven Lord
am 23 Okt. 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.
Siehe auch
Kategorien
Mehr zu Software Development Tools finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!