Methods in Scilab

Scilab supports functions defined on structures, which are similar to methods in object-oriented programming languages.

// Define a structure for rectangle
function r = rect(width, height)
    r = struct('width', width, 'height', height)
endfunction

// This 'area' function takes a rect structure as an argument
function a = area(r)
    a = r.width * r.height
endfunction

// This 'perim' function also takes a rect structure as an argument
function p = perim(r)
    p = 2*r.width + 2*r.height
endfunction

// Main function
function main()
    r = rect(10, 5)
    
    // Here we call the 2 functions defined for our structure
    printf("area: %d\n", area(r))
    printf("perim: %d\n", perim(r))
    
    // In Scilab, all variables are passed by value, so there's no need for 
    // pointer-like behavior as in some other languages
endfunction

// Execute the main function
main()

To run this program in Scilab:

--> exec('rectangle_functions.sce', -1)
area: 50
perim: 30

In Scilab, we don’t have methods directly attached to structures like in some object-oriented languages. Instead, we define functions that take the structure as an argument. This achieves a similar result to methods in other languages.

Scilab doesn’t have a concept of pointers, so all variables are passed by value. This means we don’t need to worry about the distinction between value and pointer receivers that exists in some other languages.

The struct function is used to create a structure with named fields. We then define separate functions area and perim that operate on these structures.

In the main function, we create a rectangle structure and then call our functions, passing the structure as an argument.

Next, we’ll look at how Scilab handles grouping and organizing related functions and data structures.