1

I have the following function which finds the zero of a function using Newton-Raphson:

function [ x,i ] = nr_function( x0,f,fp )

N   = 15;
eps = 1e-5;

x=x0;
for i=0:N
    if( abs(f(x))<eps )
        return;
    end

    x=x-f(x)/fp(x);
end

I can call the function like this:

f = @(x) x.^3-1
fp = @(x) 3*x.^2
nr_function(3, f,fp)

However, say I instead define my function like this, i.e. taking 2 variables:

f = @(x, q) q*x.^3-1
fp = @(x, q) q*3*x.^2

Then how would I be able to call nr_function with f and fp? I tried nr_function(3, f,fp), but that doesn't work

2
  • 1
    q in this case is defined at the call of nr_function? Commented Jul 27, 2015 at 8:39
  • @Matt Yes, it is defined when I call nr_function Commented Jul 27, 2015 at 8:41

1 Answer 1

2

If q is defined when you call nr_function, you can use an anonymous function in the call. When you do this, then the argument you pass is a new function-handle with variable x and constant q.

f  = @(x, q) q*x.^3-1
fp = @(x, q) q*3*x.^2

q = 1;

nr_function(3, @(x)f(x,q), @(x)fp(x,q))

Note: It's not necessary that you use the variable x in the anonymous function. The only importance is to have a single argument in the end. So we can use for example y as the intermediate variable like this:

nr_function(3, @(y)f(y,q), @(y)fp(y,q))

If we expand it to multiple lines, it would look like this:

f  = @(x, q) q*x.^3-1
fp = @(x, q) q*3*x.^2

q = 1;

f2  = @(y) f(y,q)
fp2 = @(y) fp(y,q)

nr_function(3, f2, fp2)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.