Search code examples
functionscilab

Scilab - define a function inside another one


I want to define a function that takes an input n and gives back the function f defined by f(x) = x^n.

So I wrote the following piece of code on Scilab:

function [f]=monomial(n)
    function [z] = g(x)
        z = x^n
    endfunction
    f = g
endfunction

Unfortunately when I evaluate monomial(3)(2) I get 32. whereas it should be 8.

I hope someone could point out where I have gone wrong when writing this function.

Could somebody help me please?


I cleared all variables and reran the code and it told me that n is not defined within g, therefore is there a way to overcome this problem?


Solution

  • the more secure way to do this is by using deff :

    function [f]=monomial(n)
        f = deff('z=g(x)','z=x^'+string(n));
    endfunction
    

    otherwise n could be polluted by current scope

    --> monomial(2)(8)
     ans  =
    
       64.