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

Matlab script for central difference

  1. Feb 5, 2015 #1

    NYK

    User Avatar

    I am trying to write a script that will compute repeatedly, beginning with step size h=1 and then progressively divide the step size by a factor of 10 to demonstrate how round-off error becomes dominant as the step size is reduced.

    In using centered difference approximation of O(h2) to estimate the first derivative at x=0.7 of:

    f(x) = -0.25x^5+0.15x^4-1.25x^3+0.35x^2+2.1x-1.4
    I have posted the script I have so far bellow:


    clear;clc;clear all

    ff=@(x) -0.25*x^5+0.15*x^4-1.25*x^3+0.35*x^2+2.1*x-1.4;
    df=@(x) -1.25*x^4+0.6*x^3-3.75*x^2+0.7*x+2.1;

    function diffex(func,dfunc,x,n)




    format long
    dftrue=dfunc(x);
    h=1;
    H(1)=h;
    D(1)=(func(x+h)-func(x-h))/(2*h);
    E(1)=abs(dftrue-D(i));
    for i=2:n
    h=h/10;
    H(i)=h;
    D(i)=(func(x+h)-func(x-h))/(2*h);
    E(i)=abs(dftrue-D(i));
    end
    L=[H' D' E']';
    fprintf(' step size finite difference round-off error\n');
    fprintf('%14.10f %16.14f %16.13f\n',L);
    loglog(H,E),xlabel('Step Size'),ylabel('Error')
    title('Plot of Error vs. Step Size')
    format short


    diffex(ff,df,0.7,11)






    Any advice, pointers or suggestions will be greatly appreciated!

    thank you
     
  2. jcsd
  3. Feb 8, 2015 #2
    What goes wrong? Can you post here the output?
     
  4. Feb 9, 2015 #3

    NYK

    User Avatar

    The error code i get is that "Function definitions are not permitted in this context", but i really dont need a function file. I have begun writing it as a regular script file.
     
  5. Feb 10, 2015 #4
    If you are not familiar with the use of the Matlab functions then you should try first the easy way: simple loop where you compute directly the function, its derivative and the corresponding error.
    If you really want to use Matlab functions you should have a look at some simple example provided by Matlab Help.
     
  6. Feb 10, 2015 #5

    kreil

    User Avatar
    Gold Member

    FYI: The error message "Function definitions are not permitted in this context" arises when you try to type a function in at the command line. That is disallowed; all functions must be saved in an mfile.

    Rewriting this to be a script rather than a function is one option, but the other way would be to just paste the code into an mfile, save the file, and then you can call the function freely.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Matlab script for central difference
  1. Create script matlab (Replies: 3)

  2. Matlab - basic script (Replies: 1)

Loading...