필터 지우기
필터 지우기

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 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