How to pass a function as argument
I'm using Scilab and I'm trying to make a function like the following:
function p = binary_search(myf,a,b)
The target is to make a binary_search
to find such p that: myf(p) = 0
in [a,b].
I want to do something like this:
root = binary_search("x^3 - 10",1,2)
Where the first string is a definition of a function.
The only way I found is defining a function called x3
:
function x = x3(p)
x = p^3 - 10;
endfunction
and then, inside binary_search
, do something like:
fa = x3开发者_高级运维(a);
Any ideas?
Thank You!
If you have defined the function f(x) = x^3 - 10
, either using deff('y=f(x)','y=x^3-10')
or the regular "function ... endfunction
" syntax, then you can simply pass f as an argument: define
function r = binary_search(f,a,b)
% do the binary search here and store the result in r
endfunction
Then you can call
---> binary_search(f, 1, 2)
which works fine in SciLab.
In MATLAB/octave, the interpreter considers " f
" as an equivalent for f()
, i.e., it would execute the function f without arguments, which will result in an error "x undefined". To avoid this, you have to type an @
in front of f:
---> binary_search( @f, 1, 2) %% in MATLAB/octave
Functions in Scilab can be passed as arguments to other functions. Therefore, if you have one function, f:
function y=f(x)
y = x^3 - 10
endfunction
you are free to pass that to another function,
root = binary_search("x^3 - 10",1,2)
deff is simply a way to quickly define a function- usually inline on the interpreter.
Alternatively, you can also pass an expression as a string to a function and have that evaluated using the evstr command:
function p = binary_search(expression, a, b)
evstr expression
//Rest of your code
endfunction
You would implement this on the interpreter thus:
expression = "a^3 - 10"
root = binary_search(expression, 1, 2)
I found a solution: In the main window (the interpreter), I define the function like:
deff('[y] = square(x)','y=x^2')
Then, I call
bi(square,0,2)
In the function, I just do 'f(x)':
function [x] = bi(f,a,b)
fa = f(a);
精彩评论