Taylor Series as a for loop

2 views (last 30 days)
Karolyn
Karolyn on 30 Sep 2013
Commented: Jan on 30 Sep 2013
I have my script written as
taylor_approx.m
x = -.5:.01:.5;
n = 10;
for k = 0:n
1/(1-x) = ((1/(1-x)) + x.^k/factorial(k));
% Gives the approx value of e^x as a taylor series
end
but it gives me the parse error "=" may not be valid MatLab syntax.
My professor sent us this to run it:
close all; clear all;
% setup the independent variable
x = -.5:.01:.5;
y = 1./(1-x);
% get the size of x
npts = numel(x);
% plot colors
colors = {'g','r','b','m','c'};
% plot the real function (sine)
plot(x,y,'k','LineWidth',2); hold on;
% calculate successively higher taylor series approximations
% higher approximations of the Taylor series
for order=1:5
T = zeros(npts,1); % zero out T
for i=1:numel(x);
T(i) = taylor_approx(x(i),order); % user defined function
end;
plot(x,T,char(colors(order)));
end;
legend('sinx','0th order','1st','2nd','3rd','4th')
  1 Comment
Jan
Jan on 30 Sep 2013
Edited: Jan on 30 Sep 2013
Your professor sent code which contains clear all? This clears all breakpoints also. And everything, which impedes debugging is a bad idea, for a professional programmer and even more for a beginner. And a lot of problems in this forum could be solved by using the debugger locally.
The shown error message is not really helpful, because we have to guess, where it occurs. In addition it is not clear, what the question is.

Sign in to comment.

Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 30 Sep 2013
What is this
1/(1-x) = ((1/(1-x)) + x.^k/factorial(k));
  2 Comments
Karolyn
Karolyn on 30 Sep 2013
The original function was f(x) = 1/(1-x), so that's the taylor series approximation for it
Azzi Abdelmalek
Azzi Abdelmalek on 30 Sep 2013
the expression in the left of = should be a name of a variable. I think you should learn the basics of programming

Sign in to comment.

Categories

Find more on Loops and Conditional Statements 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!