views:

60

answers:

2

Hi. 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 someting 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!

A: 

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);
fern17
A: 

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)
Aditya Sengupta