Sub function not replacing syms variable x with input number

조회 수: 4 (최근 30일)
Maryam Ansari
Maryam Ansari 2016년 2월 9일
답변: Walter Roberson 2016년 2월 9일
My code isn't finished yet, but this is what I have
function findTaylorSeries = TaylorCos0(valueForX,termNum)
%%formula for taylor series is sum of (n!)^-1* nth derivative of f(x)*(x-a)^2
%%where 'a' represents the center of the taylor series
%%here the taylor series is xNot = 0 = a
n = 0; %%starting at term = 0;
syms x; %%creating a symbolic variable x in order to calculate derivative of function wrt x
findTaylorSeries = 2*cos(4*x);
while n <= termNum
taylor = (factorial(n)^-1)*(diff(findTaylorSeries,n))*x^(n);
%%display(taylor);
n = n+1;
end
subs(taylor,valueForX); %%subs value for x with inputX number
display(taylor);
when I run it using another script m file, I use the inputs TaylorCos0(1,2). It iterates to the second term, which is good. My answer = -16*cos(4*x)*x^2. By using sub, I want to replace all the x values with 1 and evaluate my expression. However, the output I still receive is "-16*cos(4*x)*x^2." The symbolic x variable still remains, and I don't understand why or how to fix it.

채택된 답변

Walter Roberson
Walter Roberson 2016년 2월 9일
You need to tell subs which variable is to be substituted for. subs(taylor, x, valueForX)
Also you are discarding the result of the substitution and displaying the original expression. subs() does not change the expression being substituted into.
Thirdly, you should be totaling the terms you calculate.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Symbolic Variables, Expressions, Functions, and Settings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by