Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Octave call a function as a variable of another function

Tags:

octave

I wrote a bisection method in Octave but it can't consume another function..

My bisection method code is like:

function[x,b] = bisection(f,a,b)

  t = 10e-8

  while abs(b-a) > t;
    c = (a+b)/2;

    if f(a) * f(b) <= 0
       a = a;
       b = c;
    else 
       b = b;
       a = c
    endif
  endwhile

  x = (a+b)/2
endfunction

And I already have a file f1.m:

function y = f1(x)
  y = x^2 - 4;
endfunction

But when I call [x,v] = bisection[f1,0,5], I get:

>> [t,v] = bisection(f1,0,5)
   error: 'x' undefined near line 2 column 5
   error: called from
          f1 at line 2 column 3
   error: evaluating argument list element number 1
like image 961
Fail Analysis Avatar asked Oct 26 '25 14:10

Fail Analysis


1 Answers

what you want is to pass a pointer to f1 to your function bisection so the right call would be

[t,v] = bisection(@f1,0,5)

which outputs:

t =    1.0000e-07
a =  0.62500
a =  0.93750
a =  1.0938
a =  1.1719
a =  1.2109
a =  1.2305
a =  1.2402
a =  1.2451
a =  1.2476
a =  1.2488
a =  1.2494
a =  1.2497
a =  1.2498
a =  1.2499
a =  1.2500
a =  1.2500
a =  1.2500
a =  1.2500
a =  1.2500
a =  1.2500
a =  1.2500
a =  1.2500
a =  1.2500
a =  1.2500
x =  1.2500
t =  1.2500
v =  1.2500
like image 191
Andy Avatar answered Oct 29 '25 18:10

Andy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!