Built-in functions

A built-in function is a function provided by the interpreter system. It is compiled from C code and can be called the same way as a user defined function. For example, rand is a built-in function that that generates random numbers and matrices, length is a built-in function that returns the length of a vector or matrix, and cos is the trigonometric function cosine.
>> x = rand(5, 1);
>> length(x)
     5
>> cos(pi/4)
     0.7071067812
The complete list of the built-in functions is given in the appendix.

Like user-defined functions, built-in functions can have parameters as well. For example, the built-in function normal which generates (pseudo) random numbers of normal distribution has five parameters mu, sigma, pdf, prob, and quantile. mu and sigma are the mean and standard deviation of the distribution.

>> normal(1)
    0.5723149278
>> normal(2)
    1.64
    -0.559
>> normal.mu
    0
>> normal.sigma
    1
>> normal.prob(-inf, 0)
    0.5
The two parameters mu and sigma are modifiable. Their initial value are mu = 0 and sigma = 1 respectively. If we want a non-standard normal distribution random number generator, we may make a copy of normal and reset the values of mu and sigma
>> my_normal = normal;
>> my_normal.mu = 10;
>> my_normal.sigma = 2;
>> my_normal(1)
      8.029350953
>> my_normal(2)
      12
      10.9
>> my_normal.prob(-inf, 10)
      0.5
Note that normal is a global variable and can only be modified using the global keyword, therefore normal.mu = 10 doesn't work. But in my_normal = normal, normal does refer to the global variable normal, since here we are not trying to alter its value. The assignment my_normal = normal assigns a copy of global.normal to my_normal, which can then be modified.

It's very easy to override the definition of a built-in function. Locally defined variables have higher precedence. Once they are defined, they will replace the built-in definitions.

>> sin = x -> x - x^3 / 6;
>> sin(6)
     -30
However, an overridden built-in function is not lost. Actually all built-in functions are attributes of the global variable builtin. So they can always be accessed using builtin.name. For example
>> sin = x -> x - x^3 / 6;
>> sin(2.5*pi)
    -72.891530550
>> builtin.sin(2.5*pi)
    1

oz 2009-12-22