Some tricks on functions in Scilab

There are two ways to define functions in Scilab:

  1. using function ... endfunction
  2. using deff

Examples:


function y=my_square(x)
    y=x^2
endfunction

deff('y=my_square(x)','y=x^2')

Functions can be without arguments as well as without return values:


function f()
    disp('Hi')
endfunction

deff('g()','disp(''Hello'')')

The function ... endfunction construction is convenient if your function definition contains many lines of code.

On the other hand, because the arguments of deff are strings, it is possible to make wild manipulations redefining functions on the fly.


if n < 5 then
    function_name = 'f';
    op = '+';
else
    function_name = 'g';
    op = '-';
end

deff('z='+function_name+'(x,y)','z=x'+op+'y')

A function can call another function or even itself (this is called recursion).

The following recursive function calculates a factorial:


function y=f(n)
    if n<=1 then
        y = 1
    else
        y = n * f(n-1)
    end
endfunction

The parameters of a function can be assigned default values:


function y=f(a, b)

  [lhs,rhs] = argn(0);

  disp('Number of inputs: '+string(rhs));
  disp('Number of outputs: '+string(lhs));

  if rhs <= 1 then
       b = 10;
  end

  if rhs == 0 then
       a = 0;
       b = 10;
  end

  y = a+b;

endfunction

This is what happens if we call the function f with different number of parameters:


f()
 
 Number of inputs: 0   
 
 Number of outputs: 1   
 ans  =
 
    10.  
 
f(1)
 
 Number of inputs: 1   
 
 Number of outputs: 1   
 ans  =
 
    11.  
 
f(1,2)
 
 Number of inputs: 2   
 
 Number of outputs: 1   
 ans  =
 
    3.  

Functions can also be used as parameters in other functions. For example,


function y=f(x,fun)
    y=fun(x)
endfunction

function y=g(x)
    y = exp(x)
endfunction

f(0,g)

 ans  =
 
    1.  
 
f(1,g)

 ans  =
 
    2.7182818  

A function can be applied to each element of a vector with feval


x = [1 2 3 4 5]

 x  =
 
    1.    2.    3.    4.    5.  
 
y=feval(x,f)

 y  =
 
    1.    2.    6.    24.    120.   

Some more Scilab tricks: Scilab Bag Of Tricks

Advertisements
Published in: on 02/08/2015 at 15:27  Leave a Comment  

The URI to TrackBack this entry is: https://burubaxair.wordpress.com/2015/08/02/some-tricks-on-functions-in-scilab/trackback/

RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: