user2431438
user2431438

Reputation: 307

Replicating Simpson's rule, error with eval

I'm trying to replicate the Simpson's rule by writing a function for it. However, I'm still not clear how I could possibly use eval to transform a string to a actual function in MatLab.

The function is:

function result = simpson(fun, x0, xn, n)
    f = eval(fun);
    h = (xn-x0)/2;
    xstart = f(x0) + f(xn);
    x1 = 0;
    x2 = 0;

    for i = 1:n-1
        x = x0 + h*i;
        if (mod(i,2) == 0)
            x2 = x2 + f(x);
        else
            x1 = x1 + f(x);
        end
    end

    result = h*(xstart + 2*x2 + 4*x1)/3;

The error reported is

Error using eval
Undefined function or variable 'x'

How could I pass x to a string form of a function?

Upvotes: 0

Views: 389

Answers (2)

Alan
Alan

Reputation: 3417

The problem here is the way eval is being used. The documentation indicates that in your example the output f would not be a function handle (as is expected by the way the code uses it), but rather the output of the fun function.

So, in order to make the eval function work you need to provide it with it's input.

For example:

fun = 'x.^2';    
x = 4;    
f = eval(fun);

Results in f == 16

In short, any time you wish to call fun you would have to set x to the appropriate value, call eval and store the result.

For example, in your code:

f = eval(fun);
h = (xn-x0)/2;
xstart = f(x0) + f(xn);

Would become:

h = (xn-x0)/2;
x = x0;
fx0 = eval(fun);
x = xn; 
fxn = eval(fun);
xstart = fx0 + fxn;

I would suggest function handles as a safer and easier way of implementing this, but as mentioned in the comments this is not allowed in your case.

Upvotes: 1

DasKrümelmonster
DasKrümelmonster

Reputation: 6060

The clean way to do that: Use a function handle, avoid eval.

Function handles are documented here: http://www.mathworks.de/de/help/matlab/ref/function_handle.html

Define them like this:

sqr = @(x) x.^2;

and then call your function:

simpson(sqr, 1, 2, 3);

within your function, you should e able to call fun(3) and get 9 as a result.


If you have to use eval, I could see two solutions:

  1. The Sneaky way: simpson('@(x) x.^2') (eval creates a proper function handle)

  2. The dirty way:

    function result = simpson(fun)
        x = 4;
        f = eval(fun);
        result = f;
        return;
    end
    

Call it like this: simpson('x.^2')

Upvotes: 1

Related Questions