next up previous contents
Next: `Sci' files Up: Programming Scilab Previous: `Sce' files   Contents

Inline functions

Functions are segments of code that have well defined inputs and outputs as well as local variables. The simplest way to define a function is by using the command `deff'.

-->deff('out=half(in)','out = 0.5 * in')

-->a = 4  
 a  =
 
    4.  
 
-->half(a)
 ans  =
 
    2.  

-->half([6, 7, 4 + 5*%i])
 ans  =

!   3.    3.5    2. + 2.5i !
We defined function `half' in two strings. The first one (`out=half(in)') defines inputs and outputs; the second one (`out = 0.5 * in') constitutes the method. Notice that we defined `half' as acting on a generic `in', which can be applied to a scalar, a vector or a matrix, including real and complex values. We can define functions with different numbers of inputs and outputs


-->deff ('out = ntimes (in1, in2)', 'out = in1 * in2')

-->ntimes (3.07,3)
 ans  =

    9.21  

-->deff ('[out1, out2] = twice (in)' , ['out2 = in' , 'out1 = [in,in]'])

-->[str1 , str2] = twice ('Scilab')
 str2  =

 Scilab
 str1  =

!Scilab  Scilab  !
Notice that function `twice' includes in its method two different commands integrated as a vector of two strings. Functions can be defined without an input or an output


-->deff('out = message','out = (''It returns a string without input'') ')

-->message()
 ans  =

 It returns a string without input
We can return the inputs and outputs of a signal by naming it


-->message
 message  =

[out]=message()

-->twice
 twice  =

[out1,out2]=twice(in)
The variables inside the function are not recognized outside; to be precise, they are local.


-->deff('out = pitag (in1, in2)', ['sumcuad = in1^2 + in2^2', 'out = sqrt (sumcuad)'])

-->pitag(3,4)
 ans  =

    5.

-->sumcuad
  !--error     4
undefined variable : sumcuad
As we can nest functions, the scope of variables is a very interesting issue. I recommend the reading of `Scilab Bag Of Tricks', which explains with examples this topic as well as the reference of functions inside functions. Functions can be erased with `clear'

-->deff('out = message2','out = (''It will be erased'') ')

-->message2()
 ans  =

 It will be erased

-->clear message2

-->message2
  !--error     4
undefined variable : message2
Inline functions are appropriate for short methods. For longer ones, conventional functions are built in.
next up previous contents
Next: `Sci' files Up: Programming Scilab Previous: `Sce' files   Contents
j 2003-01-23