Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

MATLAB MATLAB Help for expansion of cos(x) using a Taylor Series

  1. Feb 11, 2010 #1
    I was hoping somebody would be able to help me as I am pretty new to Matlab. I am trying to create a for-loop to describe the taylor series expansion of cos(x)= (-1)^n*x^2n/(2n)! and to see how it converges towards cos(x). Below is the code that I have used to plot the different orders of n, but I was wondering if there was a way to make this work for any value of n?

    n=0;
    for x = -6:0.25:6
    n=n+1;
    y(n)=x;
    F(n)=cos(x);
    F0(n)=1;
    F2(n)=1-0.5*x^2;
    F4(n)=1-0.5*x^2+(1/24)*x^4;
    end
    plot(y,F,y,F0,y,F2,y,F4)
    axis([-6 6 -1.5 1.5])

    I have tried

    n=0;
    for x=(-2:.25:2)
    n=n+1;
    Y(n)=x;
    F(n)=cos(x);
    G(n)=1+(-1)^n*x^(2*n)/prod(1:2*n);
    end
    plot(y,G)

    but the plot for G does not come close to cos(x) as the values of n are not constant and the plot goes to zero. Any help would be greatly appreciated.
     
  2. jcsd
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Can you offer guidance or do you also need help?
Draft saved Draft deleted